【问题标题】:Valgrind output UnderstandingValgrind 输出理解
【发布时间】:2011-12-03 00:20:12
【问题描述】:
==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:

malloc(sizeof(some_structure) * some_expression);

在某一时刻 some_expression 给出的值是 0,所以我间接地在做

   malloc(0)

所以当我不打算 malloc 一个字节时,我不会释放它,但在这种情况下,valgrind 会显示内存泄漏。为什么?

编辑:

如果我这样使用:

char *a = malloc(0);

那么 a 不为 NULL。所以问题是为什么不为NULL? & 它存储哪个地址?

【问题讨论】:

标签: c memory-leaks malloc valgrind


【解决方案1】:

来自我的malloc(3) 手册页(Linux):

如果 size 为 0,则 malloc() 返回 NULL 或稍后可以成功传递给 free() 的唯一指针值。

因此,不能保证 malloc 在传递 0 时不会分配任何空间,如果不是 NULL,则必须将其提供给您的指针 free

如果malloc 不返回NULL,您将获得一个不能用于任何事情的缓冲区,但由于它具有唯一的地址,malloc 必须至少分配了一个字节。

也许您想将 malloc 调用替换为一个 to

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

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 2015-09-23
    • 2012-08-31
    • 1970-01-01
    • 2021-09-29
    相关资源
    最近更新 更多