1

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

BTW, you should test against failure of malloc & realloc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.