简体   繁体   English

Malloc Typedef结构问题

[英]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. 我正在构建线程库,由于某种原因遇到了一个我现在无法解决的简单malloc问题。 I'm sure it's something simple I'm just missing it. 我确定这很简单,我只是想念它。

In my main.c I have the following code: 在我的main.c中,我有以下代码:

//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 SemaVal = 5 SemaVal = 0交换

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. 您似乎无法确定谁负责分配tasem_t结构。 You have a global variable for it and pass its address to ta_sem_init . 您有一个全局变量,并将其地址传递给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. 但是,然后您有了ta_sem_init动态分配一个全新的tasem_t结构,将其地址保存到本地函数参数sema ,以便该地址超出范围时会丢失。

Pick one, either: 选择一个,或者:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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