简体   繁体   中英

Malloc Typedef Struct Problems

I am working on building a threads library and for some reason have run into a simple malloc problem that I can't fix right now. I'm sure it's something simple I'm just missing it.

In my main.c I have the following code:

//declare testSem
tasem_t testSem;


int main(int argc, char **argv){
    ta_libinit();

    //initialize testSem
    ta_sem_init(&testSem, 5);
    //wait test
    ta_sem_wait(&testSem);

the relevant code in my thread library is as follows:

void ta_sem_init(tasem_t *sema, int value)
{

    //malloc the semaphore struct
    sema = malloc(sizeof(tasem_t));

    //error check
    if(sema == NULL)
    {
        printf("could not malloc semaphore");
        exit(0);
    }

    //initialize with the given value
    sema->val = value;
    printf("SemaVal = %i\n", sema->val);
}

void ta_sem_wait(tasem_t *sema)
{
    printf("SemaVal = %i\n", sema->val);

    if(sema->val <= 0)
    {
        //not done yet
        printf("SWAPPING\n");
    }
    else
    {
        printf("SemaVal = %i\n", sema->val);
        sema->val = sema->val + 1;
    }
}

Here is the struct from my header file:

//struct to store each semas info
typedef struct tasem_t_struct
{
    //value
    int val;
        //Q* Queue
        //int numThreads


}tasem_t;

The output I get from this is:

SemaVal = 5 SemaVal = 0 SWAPPING

So evidently, I'm not mallocing my struct correctly as the value inside is lost once I go out of scope. I know I must just be forgetting something simple. Any ideas?

You can't seem to decide who's responsible for allocating your tasem_t structure. You have a global variable for it and pass its address to ta_sem_init . But then you have ta_sem_init dynamically allocate a brand new tasem_t structure, saving its address to sema , a local function argument, so that address gets lost when it falls out of scope.

Pick one, either:

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