【问题标题】:Problem with finding mistake in program with using valgrind使用 valgrind 在程序中发现错误的问题
【发布时间】:2020-02-28 19:50:30
【问题描述】:

我的程序有问题。我使用 valgrind,但我找不到问题出在哪里。我可以在代码中更改什么。这是 valgrind 中的错误:

==14892== Invalid read of size 1
==14892==    at 0x4C32D44: __strlen_sse2 (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==14892==    by 0x4EBC9D1: puts (ioputs.c:35)
==14892==    by 0x10878D: main (uloha2.c:10)
==14892==  Address 0x522d04c is 0 bytes after a block of size 12 alloc'd
==14892==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==14892==    by 0x1087D2: reverse (uloha2.c:19)
==14892==    by 0x10877D: main (uloha2.c:9)
==14892==
!DLROW OLLEH
==14892==
==14892== HEAP SUMMARY:
==14892==     in use at exit: 0 bytes in 0 blocks
==14892==   total heap usage: 2 allocs, 2 frees, 1,036 bytes allocated
==14892==
==14892== All heap blocks were freed -- no leaks are possible
==14892==
==14892== For counts of detected and suppressed errors, rerun with: -v
==14892== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

这是我的代码的一部分,可能是错误的地方。

int main(){
  char* reversed = reverse("Hello world!");
  printf("%s\n", reversed);
  free(reversed);
}

char* reverse(const char* text){
  if(text==NULL){
    return NULL;
  }

  char *novy=(char*)malloc(strlen(text));
  for(int j=0;j<strlen(text);j++){
    novy[j]=toupper(text[j]);
  }

 int p=strlen(text)-1;
 int size=strlen(text); 

 for(int i=0;i<(size/2);i++){
    char tmp=novy[i];
    novy[i]=novy[p];
    novy[p]=tmp;
    p--;
  }

  return novy;
} 

【问题讨论】:

  • char *novy=(char*)malloc(strlen(text)); ==> char *novy=malloc(strlen(text) + 1);
  • ...当您之前问过同样的question 时,建议您这样做。

标签: c valgrind reverse


【解决方案1】:

您忘记了在 C 中所有 char 字符串实际上都称为 null-terminated 字节字符串。 null-terminated 位很重要,将用于查找字符串的结尾(例如strlen)。

如果缺少字符串,函数将超出范围,您将拥有undefined behavior

空终止符是字符'\0',重要的是还要记住strlen 不计算它自己,并且它需要在您创建的字符串中留出空格:

char *novy = malloc(strlen(text) + 1);  // +1 to make room for the terminator

当然你还需要复制这个终结符:

for(int j = 0; j <= strlen(text); j++) {
    novy[j] = toupper(text[j]);
}

注意循环条件中小于 或等于运算符的使用。这将确保终止符也被复制。

【讨论】:

    猜你喜欢
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    相关资源
    最近更新 更多