mbq
mbq

Reputation: 18638

Zero bytes lost in Valgrind

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.

Upvotes: 9

Views: 4208

Answers (2)

Employed Russian
Employed Russian

Reputation: 213935

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

Upvotes: 15

Paul R
Paul R

Reputation: 213210

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

Upvotes: 1

Related Questions