我的程序有问题。我使用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;
}
您忘了在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]);
}
请注意在循环条件中使用小于 或等于运算符。这将确保终止符也被复制。