Why doesn't valgrind spot the leak when program was compiled with gcc-5.2.0

后端 未结 2 666
野性不改
野性不改 2020-12-20 03:30

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

2条回答
  •  粉色の甜心
    2020-12-20 04:03

    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...

提交回复
热议问题