Reputation: 4621
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?
Upvotes: 0
Views: 633
Reputation: 89926
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:
ta_sem_init
initialize an existing tasem_t
variable.ta_sem_init
allocate and initialize a new tasem_t
structure and then return its address (either directly or via a tasem_t**
output parameter).Upvotes: 3