Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthread_create memory leak

Tags:

c

linux

I am using C language and Linux as my programming platform.

In my app, I call pthread_create. Then I check the memory usage of my app using ps commandline tool and it adds 4 in the VSZ column.

But the problem is when the pthread_create function handler exits, the 4 that was added in the memory was not release. Then when the app call the pthread_create again, a 4 value was added again until it gets bigger.

I tried pthread_join and it seems the memory still getting bigger.

Thanks.

like image 561
domlao Avatar asked Jun 23 '26 09:06

domlao


2 Answers

ps is not the right tool to measure memory leaks. When you free memory, you are not guaranteed to decrease the process' vsize, both due to memory fragmentation and to avoid unnecessary system calls.

valgrind is a better tool to use.

like image 132
Artelius Avatar answered Jun 26 '26 02:06

Artelius


You should use either pthread_detach or pthread_join (but not both) on every pthread you create. pthread_join waits for the thread to finish; pthread_detach indicates that you don't intend to wait for it (hence the implementation is free to reclaim the storage associated with the thread when it terminates).

ditto what Artelius said about ps not being the right tool for diagnosing memory leaks.

like image 32
David Gelhar Avatar answered Jun 26 '26 00:06

David Gelhar