abcd
abcd

Reputation: 85

posix timer_create() function causing memory leak on linux

I am using timer_create function for timer functionality in my application. When timeout happens, a new thread gets created. That time my application's memory usage is getting increased by around 11mb. I also have set the thread attribute to PTHREAD_CREATE_DETACHED. Any help is appreciated. I also want to know how long will the thread that gets created when timeout happens be alive?

Minimal reproducible example:

#include <csignal>
#include <ctime>

int main(){
    struct sigevent signalEvent;
    signalEvent.sigev_notify = SIGEV_THREAD;
    signalEvent.sigev_notify_function = [](sigval_t){};
    signalEvent.sigev_notify_attributes = nullptr;
    void* timerId = nullptr;
    timer_create(CLOCK_REALTIME, &signalEvent, &timerId);
    return 0;
}

Running this with g++ main.cpp && valgrind ./a.out gives:

==4007020== LEAK SUMMARY:
==4007020==    definitely lost: 0 bytes in 0 blocks
==4007020==    indirectly lost: 0 bytes in 0 blocks
==4007020==      possibly lost: 272 bytes in 1 blocks
==4007020==    still reachable: 88 bytes in 1 blocks
==4007020==         suppressed: 0 bytes in 0 blocks

Upvotes: 1

Views: 1848

Answers (5)

ch0kee
ch0kee

Reputation: 746

Too few info given, but maybe helps:
Periodic Timer Overrun and Resource Allocation

Upvotes: 0

Nils Pipenbrinck
Nils Pipenbrinck

Reputation: 86353

I doubt it has anything to do with your timer.

If you create a new thread, the thread needs space for the stack. As far as I know this memory gets allocated once at thread creation because it has to be contiguous.

That may sound like a lot of wasted memory, but it is not. First off, you can lower the stack size if you want, second: Only the address-space inside your process gets allocated. Physical memory only gets allocated if you use the stack.

Upvotes: 1

user3458
user3458

Reputation:

Any thread stays "active" until you exit its thread function. Your leak is most probably the thread's stack - that will not go away until you invoke thread_join or some such.

Upvotes: 0

Sam Miller
Sam Miller

Reputation: 24174

Valgrind is an invaluable tool for finding memory leaks in a Linux environment

Upvotes: 1

Zan Lynx
Zan Lynx

Reputation: 54325

This question makes no sense without the code.

timer_create does not make a thread by itself. Your code must be making the thread.

Your memory leak is almost certainly caused by something wrong in your code. Since we can't see your code we can't help solve the problem.

Upvotes: 0

Related Questions