简体   繁体   中英

Is it okay to free a memory that was malloc'd in a different function?

When I have the following for the main function, race happens because of i.

...
for(i = 0; i < 30; i++){
    pthread_create(&tid[i], NULL, thread, &i);
}
...

To avoid this, I malloc'd a size of int and then used it to pass the argument instead of &i. And then I used the value and then freed it in the thread function. Does this correctly free without memory leak? (The following is the new code)

void *thread(void *vargp){
    int n = *((int *)vargp);
    free(vargp);
    pthread_detach(pthread_self());
    printf("%d\n",n);
}

void main(){
    int i;
    pthread_t tid[20];
    for(i = 0; i < 20; i++){
        int *n = (int *) malloc(sizeof(int));
        *n = i;
        pthread_create(&tid[i], NULL, thread, n);
    }
    sleep(1);
}

The short answer - yes. As long as everything you malloc ed is eventually free d once and only once, it doesn't matter that the malloc and free happen in different functions, or even different threads.

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