Is there a simple example of a false positive valgrind "possibly lost" report?

From reading the valgrind “possibly lost” memory leak report, I realized that there is very little chance that such a report would be false positive. That I could not understand how this could happen under normal circumstances without doing something very coercive for the code.

So, to understand this option, I ask if there is a simple example of a false positive valgrind of a “possibly lost” memory leak report?

+7
c ++ memory-leaks valgrind
source share
1 answer

Here is an example of a false positive "possibly lost":

class A { int x; }; class B { int y; }; class C : public A, B { int z; }; int main() { static B* notLost = new C(); //The upcast will change the pointer to point 4 bytes into the object, because that is the offset of the B subobject within the C object. //Valgrind thinks, the new object may be possibly unreachable. //But I can still do this: // delete (C*)notLost; //The downcast undoes the pointer modification by the upcast. } 

Here is a more general example of a false positive:

 //get asprintf #define _GNU_SOURCE #include <stdio.h> #include <assert.h> char* getFoo() { static char* foo = NULL; if(!foo && asprintf(&foo, "Hello World\n") < 0) assert(0); return foo; } int main() { printf("%s", getFoo()); } 

This is a typical singleton ideologist: there is somewhere a function that provides access to a special object (here the string "Hello World"), ensuring that there is only one such object ever created. Since an object is never destroyed / freed, Valgrind must think that it is a memory leak. They are usually listed as “still reachable” because there is still a static variable through which you can access, but still it is false.

+1
source share

All Articles