简体   繁体   中英

If I declare a semaphore in a malloc'd struct and I free() the struct do i still need to destroy the semaphore?

Pertaining to C programming.

Suppose i do this:

struct myStruct
{
    pthread_mutex_t myMutex;
    sem_t mySemaphore;
};

`

And i malloc the appropriate size and initialize the Semaphore:

myStruct *create_myStruct()
{
    myStruct *temp; 

    temp = (myStruct *) malloc(sizeof(myStruct));
    sema_init(&sema, 0, 0);
    pthread_mutex_init(&(temp->myMutex), NULL);
    return temp;
}

Do I still need to manually destroy the semaphore or just calling free will do?

You need to destroy both the mutex and the semaphore, and that needs to happen before you free the memory. Otherwise you have a resource leak, and your program has undefined behaviour.

You should mentally distinguish between objects and the state they represent on one hand, and the memory in which the object is stored on the other hand. Neither one knows about the other, and both need to be set up and torn down individually (and in reverse order).

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