Reputation: 13614
Referring to this construct, posting a full example would be a little too big:
__thread char* buf;
buf = malloc(1000);
Valgrind says the bytes are "definitely" lost. Shouldn't they just be "still reachable"?
Upvotes: 2
Views: 3627
Reputation: 166
This is a little like the "taste great" / "less filling" argument. Valgrind is correct AND the data is "still reachable". For instance if the data contained passwords you could 100% extract them from a heap scan. If the data started with a unique random number you could relocate it. Valgrind means you can no longer access the data through the pointer.
Upvotes: 0
Reputation: 96258
Because the allocated memory is not thread-local. It's shared by all of the threads.
The variable is, on the other hand, thread local so once it's out of scope that allocated memory will be definitely lost (if there are no copies of that pointer elsewhere.. and obviously there aren't because valgrind reports definitely lost)
You have to free
it.
Upvotes: 9
Reputation: 68033
Well, as other have said, you have to free
it.
The reasoning behind it is this: all threads share a common heap, and conceptually, memory 'ownership' can be passed between threads. One thread can malloc something, and another can free it. But, the heap has no idea who 'owns' the memory, so when your thread terminates (even if the heap remembered which thread malloc'd what) it couldn't safely delete it.
But, when your process terminates, all the heap memory is effectively 'freed' - but not individually: The entire heap of your process (which was probably just one big lump) is returned to the operating system.
Upvotes: 2
Reputation: 206526
You need to explicitly deallocate it by calling free
.
Heap allocated memory allocated by malloc
is not reclaimed until explicitly freed by calling free
. Only stack allocated local storage objects are automatically deallocated when an thread ends.
This is definitely lost because you don't have any pointer to the allocated memory once the thread exits, The pointer which points to the memory is local to the stack of the thread and it gets destroyed when thread exits, but the allocated memory is heap memory and it does not get de-allocated.
Upvotes: 2
Reputation: 36433
If the only pointer to the block is thread local, then by exiting the thread, you have lost the only pointer.
That means that it is no longer reachable = definitely lost.
Upvotes: 2