Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Valgrind does not detect leak in global pointer

I am running valgrind --leak-check=full test.cpp on the following code

#include <iostream>

int* p = new int[42]; // no leak reported

int main() 
{
    p[0] = 42; // use it
    std::cout << p[0];
}

and there is no leak reported:

==37293== LEAK SUMMARY:
==37293==    definitely lost: 0 bytes in 0 blocks
==37293==    indirectly lost: 0 bytes in 0 blocks
==37293==      possibly lost: 0 bytes in 0 blocks

Whenever I move the definition int* p = new int[42]; inside main(), so it has automatic storage duration, valgrind detects the memory leak. Why doesn't it detect the leak for static storage duration objects? Am I missing something here?

like image 403
vsoftco Avatar asked May 28 '15 05:05

vsoftco


1 Answers

They're still reachable and so are not considered leaked. If you want to show even reachable blocks, pass --leak-check=full --show-leak-kinds=all to valgrind.

Generally, this kind of "leak" is not a bug. In your example code, there is no "right place" to put a corresponding delete.

like image 79
David Schwartz Avatar answered Sep 25 '22 16:09

David Schwartz