Thread Stack leak through a recursive function

2019-08-07 03:41发布

问题:

I have following scenario, in C implementation with pthreads :

The main thread(T1) creates another thread(T2) which waits for an event.

On an event T2 calls a Tree Traversal recusive function that takes in a function pointer for an action to be executed on a Tree node. During Tree traversal, if the node is found the fn pointer is fired that creates a thread (T3), services the node and is supposed to normally die out.

I am observing a huge memory leak that comes from the T3's stack. The Valgrind tells me that

==9251== 2,720 bytes in 20 blocks are possibly lost in loss record 142 of 157

==9251==    at 0x402425F: calloc (vg_replace_malloc.c:467)

==9251==    by 0x4010CDB: _dl_allocate_tls (dl-tls.c:300)

==9251==    by 0x403A2E2: pthread_create@@GLIBC_2.1 (allocatestack.c:561)

==9251==    by 0x80571CC: serviceNode (NodeHndlr.c:432)

==9251==    by 0x804AD88: preOrderTpTraversal (treefunct.c:503)

==9251==    by 0x804AE01: preOrderTpTraversal (treefunct.c:513)

==9251==    by 0x804AE01: preOrderTpTraversal (treefunct.c:513)

==9251==    by 0x804AE01: preOrderTpTraversal (treefunct.c:513)

==9251==    by 0x8057450: serviceproc (NodeHndlr.c:519)

==9251==    by 0x403996D: start_thread (pthread_create.c:300)

==9251==    by 0x411AA4D: clone (clone.S:130)

Here the serviceproc is the T2 serviceNode is the function pointer for the Node.

Thus eventually the system runs out of vm and the thread creation fails with errorcode=11 (not enough resources)

My question is that once the the T3 (created by serviceNode) exits normally , shouldn't the thread stack be garbage collected automatically or am i missing something here. ?

Edit: or is the issue created with due to firing of the function pointer ?

回答1:

With most pthreads implementations, you will leak some memory when a thread exits unless you either:

  • Call pthread_join() that thread

    or

  • Create the thread as a detached thread, by calling pthread_detach() or as an attribute to pthread_create

Make sure you do one of the above.



回答2:

Are you sure your main problem is a memery leak? It rather seems to me that you're spawning too many threads. If you spawn a new thread in a recursivly called function, you could end up with thousands of threads. That can easily kill your application. Just think of the memory that's needed for each thread's stack.