Checking for C Leaks?


#1

When I run this in Profiler, why doesn’t it report a memory leak? Is this limited to NSObjects?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, const char * argv[])
{
    // insert code here...
    char *test = malloc(5);
    sleep(1000);
    return 0;
}

#2

It’s actually because the malloc() is being optimized out of your code by the compiler - it’s a dead store. You’re malloc-ing memory that remains unused, so the compiler decides to strip it out of the compiled product.

If you add a printf or some other functionality that makes use of your malloc’d memory, the compiler will leave your code alone and you’ll see the malloc() followed by the leak you’re looking for.

This may be more information than you’re looking for at this time (so feel free to ignore it), but I’ll leave it here anyway:
The default compiler optimization level for ‘debug’ builds (which is the default for Build & Run) is -O0, which tells the compiler not to optimize your code at all, but rather to compile it as-is. For ‘release’ builds (such as a build created for the Profiler / Instruments), the optimization level is -Os, which is the maximum (smallest/fastest) optimization level. For such release builds, the compiler is tasked with reducing the size of your code as much as possible for maximum runtime performance, which means stripping out any code that it knows with certainty doesn’t actually accomplish anything.

Hope all that helps.


#3

Excellent… thanks for the great insight!