简体   繁体   中英

C - allocating a single integer

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.

使用它的线程(因为它作为参数传递)应该在完成后释放它。

Never do this! You will lose threadNum 's value every time you loop, that's a huge memory fault! You should allocate an array with NUM_THREADS elements before the loop and free when you don't need it anymore!

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:

int *threadNums = malloc(sizeof(int) * NUM_THREADS)

for (int j = 0; j < NUM_THREADS; j++) {
  threadNum[j] = j;
  pthread_create(..., (void *)&threadNum[j]);
} 

//something to ensure the threads are done using the memory

free(threadNums);

(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.

How about this: create an array of NUM_THREADS size, and with each iteration you can assign j to the jth index in the array. Then you can pass the address of the array index to each pthread_create call, and it would also not require any dynamic allocation.

You should simply write your code like this:

for (int j = 0; j < NUM_THREADS; j++)
{
     pthread_create(..., (void *)j);
}

Then there is no allocation involved. Cast the thread start function's argument back to (int) to use it. Since you're using pthread_create , you're targetting a POSIX system, which means you don't have to deal with all the nonsense plain C allows whereby this type of casting might not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM