Mihir Shah
Mihir Shah

Reputation: 29

How to stop the old variable from getting overwritten in C method?

I am declaring a struct node and instantiating it with some values in a method. The print statement in the add_map method returns the same for both calls of the method.

I want them to point to different locations of memory and retain the values allocated.

How can I fix this? Thank you!

int main()
    // ... Ptr and ptr2 are two different buffers, st is the pointer 
    // to the hash table.

    add_map(ptr, st, n);
    add_map(ptr2, st, a);
    printf("%-d\n", buf_getint(ptr, st));
    printf("%-d\n", buf_getint(ptr2, st));    
}

// source file

void add_map(struct buf* bst, struct node** ptr, uint8_t val) {
    int8_t hash_val;
    hash_val = hash_str(bst);
    struct node* pt;
    pt = *(ptr + hash_val);
    while (pt != NULL) pt = pt->ptr;
    struct node new_item = {.val = val, .buf = *bst, .ptr = NULL};
    new_item.buf.pos = bst->pos;
    printf("\n%x\n", &new_item);
    *(ptr + hash_val) = &new_item;
}

Upvotes: 0

Views: 165

Answers (1)

BearAqua
BearAqua

Reputation: 528

In your add_map function,

struct node new_item = {.val = val, .buf = *bst, .ptr = NULL};

is a local stack-initialized variable which will go out of scope when you exit the function (i.e. the content your pointer points to will become gibberish). You should use manual memory management (malloc()/free()) to allocate your struct inside add_map. If I understood your question correctly, this would also solve your problem.

Upvotes: 1

Related Questions