Aaron
Aaron

Reputation: 4480

Not sure why global variable is not changing

In the following function I call add_to_list with two globals ptr and tcb.

In add_to_list if ptr does not exist it mallocs the memory for it and attaches a previous and next node.

This works inside of add_to_list, but when I leave tcb acts like a local variable and is null. When I call add_to_list again it treats ptr as if it is null.

tcb is initialized to null outside of the add_to_list function, but its passed in as a pointer so wouldn't that make changes done at that address make it a global?

What am I doing so the changes do stick to tcb instead of the next time I go call add_to_list tcb is null.

struct TCB_t *ptr = NULL;
struct TCB_t *tcb = NULL;

void start_thread(void (*function)(void))
{
    printf("In main: creating thread\n");
    struct stack * stackP = (struct stack*)malloc(8192);
    tcb = (struct TCB_t *)malloc(sizeof(struct TCB_t));
    init_TCB (tcb, function, stackP,  8192);
    add_to_list( ptr, tcb);
}

struct TCB_t* create_list()
{
    return (struct TCB_t*)malloc(sizeof(struct TCB_t));
}

void add_to_list( struct TCB_t *ptrBlock, struct TCB_t * addQ)
{
    addQ->val =iter;
    iter++;

    if(!ptrBlock)
    {
        ptrBlock = create_list();
        ptrBlock = addQ;
        ptrBlock->next = ptrBlock;
        ptrBlock->previous = ptrBlock;
    }
}

Upvotes: 0

Views: 87

Answers (2)

John Bollinger
John Bollinger

Reputation: 181849

You are passing the pointer variables ptr and tcb by value (as indeed is the only way any argument is passed in C). If you want to be able to modify those variables via your function, then you must pass pointers to them:

void start_thread(void (*function)(void))
{
    /* ... */
    add_to_list( &ptr, &tcb);
}


void add_to_list( struct TCB_t **ptrBlock, struct TCB_t **addQ)
{
    *addQ->val =iter;
    iter++;

    if(!*ptrBlock)
    {
        *ptrBlock = create_list();
        *ptrBlock = addQ;
        *ptrBlock->next = *ptrBlock;
        *ptrBlock->previous = *ptrBlock;
    }
}

Upvotes: 2

radar
radar

Reputation: 13425

you need to pass the address , the function declaration would become

void add_to_list( struct TCB_t **ptrBlock, struct TCB_t ** addQ)

As they are global, you can actually access them directly with out passing them as function arguments too

Upvotes: 1

Related Questions