tags:

views:

35

answers:

1

As title said,Can i treat the output of valgrind memcheck, "possibly lost" as "definitely lost" ?

# Possibly lost, or “dubious”: A pointer to the interior of the block is found. The pointer might originally have pointed to the start and have been moved along, or it might be entirely unrelated. Memcheck deems such a block as “dubious”, because it's unclear whether or not a pointer to it still exists.
# Definitely lost, or “leaked”: The worst outcome is that no pointer to the block can be found. The block is classified as “leaked”, because the programmer could not possibly have freed it at program exit, since no pointer to it exists. This is likely a symptom of having lost the pointer at some earlier point in the program
+1  A: 

possibly lost can happen when you traverse an array using the pointer holding it, knowing you can reset the pointer by subtracting the index. valgrind can only guess whether you are doing this deliberately, or whether it is a programming error. that's why it warns you.

i say you should treat possibly lost as severe as definitely lost. in other words, fix your code until there are no losts at all.

example

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char** argv) {
  char* s = "string";
  char* p = strdup(s);
  p += 1;
  // trigger segfault here
  *s = 'S';
  p -= 1;
  free(p);
  return 0;
}

compile

$ gcc -ggdb foo.c -o foo

valgrind report

$ valgrind ./foo
...
==3415== Command: ./foo
==3415== 
==3415== 
==3415== Process terminating with default action of signal 11 (SIGSEGV)
==3415==  Bad permissions for mapped region at address 0x80484E0
==3415==    at 0x804840E: main (foo.c:9)
==3415== 
==3415== HEAP SUMMARY:
==3415==     in use at exit: 7 bytes in 1 blocks
==3415==   total heap usage: 1 allocs, 0 frees, 7 bytes allocated
==3415== 
==3415== LEAK SUMMARY:
==3415==    definitely lost: 0 bytes in 0 blocks
==3415==    indirectly lost: 0 bytes in 0 blocks
==3415==      possibly lost: 7 bytes in 1 blocks
==3415==    still reachable: 0 bytes in 0 blocks
==3415==         suppressed: 0 bytes in 0 blocks
...

running the code without the segmentation fault will cause valgrind to report no memory losses.

this is a trivial example. in sufficiently complicated code it is no longer obvious that the pointer can and will return to the beginning of the memory block. changes in other part of the code can cause the "possibly lost" to be a "definitely lost".

lesmana
thanks lesmana for detailed explanation.
lakshmipathi