/usr/bin/leaks Still Reachable Leak Detection

Consider the following program, memory-leak.c:

#include <stdlib.h>
void *p;
int main() {
  p = malloc(7);
  p = 0; // The memory is leaked here.
  return 0;
}

If I compile this with clang memory-leak.c and test the output with the built-in MacOS memory leak detector leaks using leaks -quiet -atExit -- ./a.out, I get (partly) the following output:

1 leak for 16 total leaked bytes.

However, if I remove the 'leaking' line like so:

#include <stdlib.h>
void *p;
int main() {
  p = malloc(7);
  return 0;
}

Compiling this file and again running leaks now (partly) returns:

0 leaks for 0 total leaked bytes.

The man page for leaks shows that it is only un-reachable memory that is considered a leak. Is there a configuration to detect un-free'd reachablemalloc segments?

Answered by DTS Engineer in 776099022

leaks works like a mark-and-sweep garbage collector, that is, it chases object pointers from a set of roots. Candidates for roots include all global variables and all thread stacks. It’s likely that, in the second case, the local variable p still exists on the stack and contains a pointer to your block, and thus leaks thinks that the allocated block is reachable.

Unlike a ‘real’ garbage-collected language, leaks has to deal with all the wackiness inherent in C-based languages, and thus it can suffer from false positives and false negatives. Such is life (kerplunk!).

Is there a configuration to detect un-free'd reachable malloc segments?

Check out the heap tool.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Accepted Answer

leaks works like a mark-and-sweep garbage collector, that is, it chases object pointers from a set of roots. Candidates for roots include all global variables and all thread stacks. It’s likely that, in the second case, the local variable p still exists on the stack and contains a pointer to your block, and thus leaks thinks that the allocated block is reachable.

Unlike a ‘real’ garbage-collected language, leaks has to deal with all the wackiness inherent in C-based languages, and thus it can suffer from false positives and false negatives. Such is life (kerplunk!).

Is there a configuration to detect un-free'd reachable malloc segments?

Check out the heap tool.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Thanks for the in-depth answer on leaks @eskimo!

What is the equivalent to -atExit -- for heap?

/usr/bin/leaks Still Reachable Leak Detection
 
 
Q