2011-10-07 70 views
1
==20420== 
==20420== HEAP SUMMARY: 
==20420==  in use at exit: 0 bytes in 1 blocks 
==20420== total heap usage: 1 allocs, 0 frees, 0 bytes allocated 
==20420== 
==20420== Searching for pointers to 1 not-freed blocks 
==20420== Checked 48,492 bytes 
==20420== 
==20420== 0 bytes in 1 blocks are still reachable in loss record 1 of 1 
==20420== at 0x400677E: malloc (vg_replace_malloc.c:195) 
==20420== by 0x80483D8: main (jig.c:10) 
==20420== 
==20420== LEAK SUMMARY: 
==20420== definitely lost: 0 bytes in 0 blocks 
==20420== indirectly lost: 0 bytes in 0 blocks 
==20420==  possibly lost: 0 bytes in 0 blocks 
==20420== still reachable: 0 bytes in 1 blocks 
==20420==   suppressed: 0 bytes in 0 blocks 

見我的項目,我用malloc這樣的:Valgrind的輸出瞭解

malloc(sizeof(some_structure) * some_expression); 

在一個點some_expression給出值0,這樣間接地我做

malloc(0) 

所以,當我不去malloc單個字節,所以我不釋放它,但在這種情況下valgrind顯示內存泄漏。爲什麼?

編輯:

如果我用這樣的:

char *a = malloc(0); 

然後一個不爲空。所以問題是爲什麼不是NULL? &它存儲哪個地址?

+0

的[零字節在Valgrind的丟失]可能重複(http://stackoverflow.com/questions/5498395/zero-bytes-中損失的Valgrind的) –

回答

6

從我malloc(3)手冊頁(Linux的):

如果大小爲0,則malloc()回報要麼NULL,或者以後可以順利通過,以free()的唯一指針值。

所以沒有保證malloc當你通過它爲0,則不分配任何空間,你必須free,它給你,如果它是不NULL指針。

如果malloc不返回NULL,你,你不能對任何使用緩衝區,但是因爲它有一個唯一的地址,malloc必須至少分配一個字節。

也許你會想更換malloc電話與一個

// like malloc, but guarantees NULL return value if n==0 
void *malloc0(size_t n) 
{ 
    return n ? malloc(n) : NULL; 
}