【发布时间】: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 时,建议您这样做。