开发者

Valgrind output Understanding

开发者 https://www.devze.com 2023-04-11 23:38 出处:网络
==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== 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

See in my project I use malloc like this:

malloc(sizeof(some_structure) * some_expression);

at one point some_expression gives value 0 so indirectly i am doing

   malloc(0)

So when I am not going to malloc a single byte so I am not making free it but in that case valgrind shows memory leackage. Why?

Edit :

If I use like this:

char *a = malloc(0);

Then a is not NULL. So questi开发者_运维问答on is why not NULL? & Which address it stores?


From my malloc(3) manpage (Linux):

If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

So there's no guarantee that malloc is not allocating any space when you pass it 0, and you have to free the pointer that it gives you if it isn't NULL.

If malloc does not return NULL, you get a buffer that you can't use for anything, but since it has a unique address, malloc must have allocated at least one byte.

Maybe you'd want to replace the malloc call with one to

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号