[英]C: try to assign string literal “abc” to an array of size 3, valgrind detects error
[英]C - Valgrind detects an error in my reverse-string function
我寫了一個看起來不錯的小程序,但是當我運行memcheck時,valgrind給了我一個奇怪的錯誤。 我需要幫助來解釋錯誤代碼:)
#include <stdio.h>
#include <stdlib.h>
int get_length(char* str){
int i=0;
char c = str[0];
while(c!='\0'){
i++;
c=str[i];
}
return i;
}
char* rev(char* str){
int length = get_length(str);
char* x=malloc(length*sizeof(char));
int i;
length-=1;
for(i=0; i<=length; i++){
x[i]=str[length-i];
}
return x;
}
int main(){
char* s=rev("roma");
printf("%s\n",s);
free(s);
}
valgrind輸出如下:
Invalid read of size 1
==14727== at 0x4C29724: __GI_strlen (mc_replace_strmem.c:405)
==14727== by 0x4E9907A: puts (ioputs.c:37)
==14727== by 0x400673: main (in /home/francesco80b/Scrivania/i_a/l-04/main.o)
==14727== Address 0x51ba044 is 0 bytes after a block of size 4 alloc'd
==14727== at 0x4C28D84: malloc (vg_replace_malloc.c:291)
==14727== by 0x400601: rev (in /home/francesco80b/Scrivania/i_a/l-04/main.o)
==14727== by 0x400663: main (in /home/francesco80b/Scrivania/i_a/l-04/main.o)
==14727==
amor
==14727==
==14727== HEAP SUMMARY:
==14727== in use at exit: 0 bytes in 0 blocks
==14727== total heap usage: 1 allocs, 1 frees, 4 bytes allocated
==14727==
==14727== All heap blocks were freed -- no leaks are possible
我還注意到,如果我使用calloc()而不是malloc(),則valgrind根本不會檢測到任何錯誤。
注意:我寫了get_length()函數只是為了好玩,大聲笑
您分配的字符數少於所需:
char* x=malloc(length*sizeof(char));
應該
char* x=malloc(length+1);
不需要乘以sizeof(char)
,因為標准要求它是1
。 需要加1
,因為您需要為空終止符添加一個額外的字符,您的函數無法添加該字符。 這就是為什么在printf
嘗試打印字符串時發生無效讀取的原因。
要解決此問題,請分配length+1
,並添加x[length] = '\\0';
從函數返回x
之前。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.