Search code examples
cpointersmallocdynamic-memory-allocationrealloc

Errors when making a dynamic C array of structs


I have a struct called Collection:

typedef struct collection {
   char *type;
   char *arg;
} *Collection;

And I would like to have a dynamic array of this struct (or rather, of pointers to instances of this struct). This is what I tried:

Collection *rawCollections = malloc(0);
int colCounter = 0;
while (i < argc) {
    Collection col = malloc(sizeof(Collection));
    // code to fill in Collection
    rawCollections = realloc(rawCollections, sizeof(rawCollections) + sizeof(Collection));
    rawCollections[colCounter] = col;
    colCounter++;
}

My reasoning is that we will add sizeof(Collection) to the array each time I need to add another one. I am getting these errors, and I am not sure why:

realloc(): invalid next size
Aborted (core dumped)

Solution

  • You must compute the new size for the array by multiplying the size of the array element (a pointer to a struct collection) by the new number of elements (colCounter + 1).

    Note also how confusing it is to hide pointers behind typedefs: sizeof(Collection) is not the size of the structure.

    Here is a modified version:

    struct collection **rawCollections = NULL;  // no need for `malloc(0)`
    int colCounter = 0;
    while (i < argc) {
        struct collection *col = malloc(sizeof(*col));
        // code to fill in Collection
        rawCollections = realloc(rawCollections, sizeof(*rawCollections) * (colCounter + 1));
        rawCollections[colCounter] = col;
        colCounter++;
    }