0

I wrote the following piece of code as an xcode command line tool in c++

int * num = new int[100];

num[4] = 5;
num = NULL;

cout << "leaked" << endl;

string c; cin >> c;

return 0;

However, when profiling using Instruments with the Leaks template, it does not show any memory leaks, although there should clearly be one while it is waiting for input. enter image description here

1110101001
  • 4,662
  • 7
  • 26
  • 48

1 Answers1

3

When you compile for profiling, the compiler does optimizations. One of those optimizations is dead-store optimization:

num = NULL; // The optimizer deleted this operation

Normally, why would you care if num actually equals NULL? Since you never read the value of num, you have no way of knowing if the compiler actually stored NULL there without looking at the assembly output. So the compiler doesn't bother actually writing NULL to that location.

But wait, there's more

I did a test:

#include <unistd.h>
int main()
{
    int *num = new int[100];
    num[4] = 5;
    num = NULL;
    sleep(1);
    return 0;
}

The assembly (prologue and epilogue omitted for brevity):

movl    $1, %edi
callq   _sleep
xorl    %eax, %eax

Wait a darn minute, what happened to new int[100] and num[4] = 5?

The entire allocation got optimized out, because the compiler figured out a way to get the same result without allocating anything. Compilers are amazing, aren't they?

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
  • So to avoid this I should read from `num` after I assign it as `NULL`? – 1110101001 Jun 10 '14 at 23:38
  • @user2612743: That might be enough to keep the variable live. Although the lesson here is that you shouldn't trust the results you get from toy programs :-) – Dietrich Epp Jun 10 '14 at 23:44