2014-05-17 31 views
1

我寫了一個似乎能正常工作的小程序,但是當我運行memcheck時,valgrind給了我一個奇怪的錯誤。我需要幫助解釋錯誤代碼:)C-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 

我也注意到,如果我使用的,而不是使用malloc()釋放calloc(),Valgrind的不檢測到任何錯誤。

注:我寫的get_length()只是爲了好玩功能,笑

回答

4

您分配較少的字符比你需要:

char* x=malloc(length*sizeof(char)); 

應該

char* x=malloc(length+1); 

通過sizeof(char)乘是不必要,因爲標準要求它是1。需要添加1,因爲您需要爲空終止符添加一個額外的字符,而該函數無法添加。這就是當printf嘗試打印字符串時發生無效讀取的原因。

要解決此問題,請分配length+1,並在函數返回x之前添加x[length] = '\0';