Today I was coding something and after I was done, I made a check with valgrind and I got a surprise.
If I compile my program on my Ubuntu (15.04 64BIT) with gcc-4.9
Seems that GCC 5.2.0 is able to detect that string2
is a constant "Hello"
through the strcpy
. So it just optimizes out string2
without allocating new memory chunk in the HEAP. My guess would be that string.h
has the implementation of strcpy
and strlen
in the header itself.
The best way to detect memory leaks is to compile without optimizations. Try recompiling it with -O0
instead of -O2
. In this case the compiler will create the binary as close to your source code as possible.
With this:
printf("String2 = %s\n",string2);
The leak is spotted:
Here it seems that the compiler detects dependency on string2
so it doesn't optimize it out. Probably because the implementation of printf
is not available at the compilation time of your source or maybe because printf
uses variadic variable. But it is just my guess...