I saw that valgrind classifies memory leaks into:
Some examples of what the documentation are different libraries that have their own allocators and for which the memory returned is not directly the pointer returned by the underlying OS allocator (malloc/sbrk), but a pointer after an offset. Consider for example, an allocator that obtained some extra memory and stored meta information (maybe type information for a garbage collector...). The process of allocation and deallocation would be similar to:
void* allocate( size_t size ) {
metainfo_t *m = (metainfo_t*) malloc( size + sizeof(metainfo) );
m->data = some_value;
return (void*)(m+1); // [1]
}
void deallocate( void* p ) {
metainfo_t *m = ((metainfo_t*)p) - 1;
// use data
}
void * memory = allocate(10);
When valgrind is tracking the memory, it remembers the original pointer that was returned by malloc
, and that pointer is not stored anywhere in the program. But that does not mean that the memory has been leaked, it only means that the pointer is not directly available in the program. In particular memory
still holds the returned pointer, and deallocate
can be called to release it, but valgrind
does not see the original returned pointer at location (char*)memory - sizeof(metadata_t)
anywhere in the program and warns.