Before you edit to add pthread_exit(0) to the end of main() your program will exit before all threads have finished. valgrind thus reported resources that were still supported by threads that were still active at the time the program ended, making it look like your memory leak.
Calling pthread_exit(0) on main() calls the main thread, waiting for all other spawned threads to complete before it exits. This allows valgrind observe a clean run in terms of memory usage.
(I assume Linux is your operating system below, but it looks like you are using some UNIX from your comments.)
The extra virtual memory you see is just linux, which assigns some pages to your program, since it was a large memory user. As long as the usage of your resident memory is low and constant, when you reach a state of inactivity, and the virtual use is relatively constant, you can assume that your system is behaving well.
By default, each thread receives 2 MB of stack space in linux. If each thread stack does not require so much space, you can adjust it by initializing pthread_attr_t and setting it with a smaller stack size using pthread_attr_setstacksize() . What size of the stack is appropriate depends on how much your function call stack grows and how much space the local variables for these functions take.
#define SMALLEST_STACKSZ PTHREAD_STACK_MIN #define SMALL_STACK (24*1024) pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, SMALL_STACK); pthread_create(&my_thread, &attr, run_thread, (void *)thread_count); pthread_attr_destroy(&attr);
source share