Zero bytes lost in Valgrind

安稳与你 提交于 2020-01-23 05:58:15

问题


What does it mean when Valgrind reports o bytes lost, like here:

==27752== 0 bytes in 1 blocks are definitely lost in loss record 2 of 1,532

I suspect it is just an artifact from creative use of malloc, but it is good to be sure (-;

EDIT: Of course the real question is whether it can be ignored or it is an effective leak that should be fixed by freeing those buffers.


回答1:


Yes, this is a real leak, and it should be fixed.

When you malloc(0), malloc may either give you NULL, or an address that is guaranteed to be different from that of any other object.

Since you are likely on Linux, you get the second. There is no space wasted for the allocated buffer itself, but libc has to do some housekeeping, and that does waste space, so you can't go on doing malloc(0) indefinitely.

You can observe it with:

#include <stdio.h>
#include <stdlib.h>
int main() {
  unsigned long i;
  for (i = 0; i < (size_t)-1; ++i) {
    void *p = malloc(0);
    if (p == NULL) {
      fprintf(stderr, "Ran out of memory on %ld iteration\n", i);
      break;
    }
  }
  return 0;
}

gcc t.c && bash -c 'ulimit -v 10240 && ./a.out'
Ran out of memory on 202751 iteration



回答2:


It looks like you allocated a block with 0 size and then didn't subsequently free it.



来源:https://stackoverflow.com/questions/5498395/zero-bytes-lost-in-valgrind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!