bustedware
bustedware

Reputation: 324

Cannot realloc c array of structs

I have a structs like so

typedef struct ll_node {
    uint data;
    struct ll_node* next;
} ll_node;

typedef struct {
    ll_node* head;
    uint     count;
} linked_list;

typedef struct {
    linked_list* lists;
    uint list_size
} Context;

And I need to be able to have lists grow dynamically from context. Here is how I'm adding a linked list to my lists array

void add_list(Context* c) {
    if (c->list_size == 0) {
        c->lists = malloc(sizeof(linked_list));
    } else {
        realloc(c->lists, sizeof(linked_list) * (c->list_size + 1));
    }
    linked_list_init(c->lists[c->list_size]);
    list_size++;
}

The problem comes in whenever I realloc. I lose the data that is not the most current index in lists. So if c->lists[0] contained 1==>1==>2 then it would be gone and c->lists[1] would be initialized and ready for linked list functions.

Any help would be greatly appreciated

Upvotes: 1

Views: 249

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

this is wrong

realloc(c->lists, sizeof(linked_list) * (c->list_size + 1));

should be

c->lists = realloc(c->lists, sizeof(linked_list) * (c->list_size + 1));

and I would recommend a safe way of doing this

void *clists;

clists = realloc(c->lists, sizeof(linked_list) * (c->list_size + 1));
if (clists == NULL)
    handleCurrentErrorProbablyRetryOrAbortFillingTheListAndCleanupResources();
c->lists = clists

this way you wont overwrite the valid c->list in case of failure.

tip: don't update c->list_size unless the malloc or realloc was successful, you need to check that the return non-NULL.

Upvotes: 4

Related Questions