I have noticed that when I call a method using a thread in the form
////main code/////
pthread_t thread;
pthread_create(thread,function,data);
//////////////////
void* function(void* data){
//work with some data on the heap via a vector on the stack
std::vector<double> variable (100,1.2345);
//do contents of thread
pthread_exit(NULL);
}
despite having no calls to new
(except implicitly in vector variable) I get a memory leak with the amount of memory usage going linearly with the number of times I call function
in this way.
However if I do this
void* function(void* data){
{
std::vector<double> variable (100,1.2345);
//do contents of thread
}
pthread_exit(NULL);
}
the memory leak doesn't occur.
It seems that pthread_exit(NULL)
doesn't clear the stack variables like you would get at the end of a normal function with return
(I am correct about that right?!) so putting them within their own scope ensures they get freed.
However, this seems like a massive kludge. How do I ensure the stack variables (and their contents on the heap in terms of containers) are cleared properly when exiting a pthread?