2014-01-05 78 views
1

所以基本上我的輸入是一個未知大小的字符串。 我所做的是創建一個函數來掃描它併爲每個字符動態分配內存。動態字符串內存泄漏

char* GetUnknownStr(){ 
char* string = NULL; 
char input = 0; 
int charCount = 0; 
//scan for chars until ENTER is pressed 
while (input != '\n'){ 
    scanf("%c", &input); 
    //on last iteration (when ENTER is pressed) break from loop 
    if (input == '\n') 
     break; 
    //realloc new amount of chars 
    string = (char*)realloc(string, (++charCount)*sizeof(char)); 
    //check if realloc didnt fail 
    if (string == NULL){ 
     puts("failed to allocate"); 
     return 0; 
    } 
    //assign char scanned into string 
    string[charCount-1] = input; 
} 
//realloc 1 more char for '\0' in the end of string 
string = (char*)realloc(string, (++charCount)*sizeof(char)); <--leak 
string[charCount-1] = '\0'; 
return string; 
} 

的valgrind:

==30911== HEAP SUMMARY: 
==30911==  in use at exit: 4 bytes in 1 blocks 
==30911== total heap usage: 7 allocs, 6 frees, 16 bytes allocated 
==30911== 
==30911== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1 
==30911== at 0x4A05255: realloc (vg_replace_malloc.c:476) 
==30911== by 0x40091F: GetUnknownStr (in /u/stud/krukfel/C/e5/a.out) 
==30911== by 0x40266B: main (in /u/stud/krukfel/C/e5/a.out) 
==30911== 
==30911== LEAK SUMMARY: 
==30911== definitely lost: 4 bytes in 1 blocks 
==30911== indirectly lost: 0 bytes in 0 blocks 
==30911==  possibly lost: 0 bytes in 0 blocks 
==30911== still reachable: 0 bytes in 0 blocks 
==30911==   suppressed: 0 bytes in 0 blocks 
==30911== 
==30911== For counts of detected and suppressed errors, rerun with: -v 
==30911== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 6 from 6) 

由於某種原因,即時得到了內存泄漏,不能找出原因,使用Valgrind的嘗試,但不可能從它什麼太大的意義。 謝謝!

+1

Valgrind告訴你什麼? –

+0

你怎麼知道你第一次有泄漏? – Devolus

回答

2

除了小的文體問題,如鑄造malloc和乘以sizeof(char),你的代碼是好的。實際的泄漏是在調用你的函數的代碼中。

處理內存泄漏的中心問題是擁有權。一旦知道誰擁有分配的內存塊,就知道需要釋放哪些內容以避免泄漏。在這種情況下,該字符串在GetUnknownStr內部創建,但是該字符串的所有權將轉移給調用者。它是您的GetUnknownStr函數的調用者,負責調用free函數返回的結果。如果主叫方未釋放該字符串,則會報告泄漏。泄漏的位置將是最後一次重新分配的位置,即您在代碼中標記的行。

+0

好吧,基本上發生的是,我用它來掃描一個字符串(主),然後立即釋放它。 –

+0

@FelixKreuk它看起來像調用者(即你的'main')跳過這些調用中的一個來釋放字符串。如果這是'realloc'的唯一函數,那麼看起來您已經調用了它七次。用戶最後一次輸入三個字母(可能是「再見」命令?),此時'main'退出而不調用'free'。 – dasblinkenlight

+0

謝謝!就是這樣! –