1

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)
chqrlie
  • 131,814
  • 10
  • 121
  • 189
shurup
  • 751
  • 10
  • 33

1 Answers1

2

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++;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • `sizeof(Collection)` is the size of the pointer to the structure, correct? – shurup Sep 11 '20 at 21:53
  • 1
    @shurup: yes it is, but you write `Collection col = malloc(sizeof(Collection));` which is incorrect: you should allocate the space for a structure, not the space for a pointer. – chqrlie Sep 11 '20 at 22:01