Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 324
mbq Avatar asked Mar 31 '11 10:03

mbq


People also ask

What is possibly lost in Valgrind?

possibly lost: heap-allocated memory that was never freed to which valgrind cannot be sure whether there is a pointer or not. still reachable: heap-allocated memory that was never freed to which the program still has a pointer at exit (typically this means a global variable points to it).

What is indirectly lost in Valgrind?

"indirectly lost" means your program is leaking memory in a pointer-based structure. (E.g. if the root node of a binary tree is "definitely lost", all the children will be "indirectly lost".) If you fix the "definitely lost" leaks, the "indirectly lost" leaks should go away.

Are still reachable in loss record Valgrind?

The "still reachable" category within Valgrind's leak report refers to allocations that fit only the first definition of "memory leak". These blocks were not freed, but they could have been freed (if the programmer had wanted to) because the program still was keeping track of pointers to those memory blocks.

How does Valgrind detect memory corruption?

To get the details you need, add --show-leak-kinds=reachable or --show-leak-kinds=all to the Valgrind command line (together with --leak-check=full ). Now you will also get backtraces showing where still reachable memory blocks were allocated in your program.


2 Answers

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
like image 188
Employed Russian Avatar answered Sep 28 '22 07:09

Employed Russian


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

like image 20
Paul R Avatar answered Sep 28 '22 07:09

Paul R