0

我正在构建一个线程库,由于某种原因遇到了一个我现在无法修复的简单 malloc 问题。我确定这很简单,我只是想念它。

在我的 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);

我的线程库中的相关代码如下:

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;
    }
}

这是我的头文件中的结构:

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


}tasem_t;

我从中得到的输出是:

SemaVal = 5 SemaVal = 0 交换

很明显,我没有正确分配我的结构,因为一旦超出范围,内部的值就会丢失。我知道我一定只是忘记了一些简单的事情。有任何想法吗?

4

1 回答 1

3

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:

于 2013-04-07T19:42:41.367 回答