Search code examples
memory-leaksvalgrind

Memory leakage :Definitely lost and possibly lost


When i am running valgrind by adding a leakage to my code,I am getting leakage as still reachable for first allocation of block and then showing as definitely lost for 9 blocks.Possibly lost is showing due to other portion of the code. Why is this so ?

main()
{
........

char *ptr;
For(i=0;i<10;i++)
{
ptr=malloc(sizeof * ptr);
}

.....

}

Report:

HEAP SUMMARY:
==13832==     in use at exit: 202,328 bytes in 62 blocks
==13832==   total heap usage: 332 allocs, 270 frees, 283,928 bytes allocated
==13832==
==13832== LEAK SUMMARY:
==13832==    definitely lost: 90 bytes in 9 blocks
==13832==    indirectly lost: 0 bytes in 0 blocks
==13832==      possibly lost: 202,180 bytes in 49 blocks
==13832==    still reachable: 58 bytes in 4 blocks
==13832==         suppressed: 0 bytes in 0 blocks
==13832== Rerun with --leak-check=full to see details of leaked memory

Solution

  • Adding to Florian's answer, here are a few examples of where you would have interior pointers

    1. A memory manager. For instance, you know that you are going to be allocating very many small blocks of memory of the same size, so you write a memory manager that allocates large blocks and the subdivides them into your small size. These sub-block allocations are interior pointers.
    2. A memory debugger. In this case, you allocate more memory than requested, and the extra memory is used to pad the allocated memory. The pointer returned to the client is an interior pointer.
    3. Data structures such as Pascal strings. Here you allocate memory for the string and its size. The size comes before the string so the pointer to the start of the string is an interior pointer.