I’m experimenting with pthread library and I’ve got the following piece of code:
for (int j = 0; j < NUM_THREADS; j++)
{
int *threadNum = malloc(sizeof(int));
*threadNum = j;
pthread_create(..., (void *)threadNum);
}
Since there is no free, this code has a memory leak. Where should I place free to avoid memory leaks? If I simply write something like:
int *threadNum = 0;
*threadNum = j;
This leads to a segfault. And I can’t place free inside the scope, because I’m using pthread_join in the next few lines.
You should call free when you’re no longer using your allocated memory.
Presumably, that’s after your join, but since your integers are allocated inside the loop, you would need to keep a reference outside the loop.
Rather than allocating your integers individually, consider allocating all of them at once, outside the loop:
(Not tested for syntax errors, but hopefully you get the idea)
Pay special attention to the comment. If your threads are not done with the memory before you call free, you have a race condition which causes undefined behavior. One way of ensuring that is to join all of the threads.
Alternatively, if the data is only used be the thread, the thread could be responsible for freeing the memory – in that case, you call free on your pointer when the thread function no longer needs it.