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)
8
  • 1
    sizeof(rawCollections) does not change. Commented Sep 11, 2020 at 21:28
  • You need to keep your own counter for the size to reallocate (for example colCounter). Commented Sep 11, 2020 at 21:31
  • 4
    Do not hide pointer nature behind a typedef. It confuses everyone, including you. Commented Sep 11, 2020 at 21:36
  • 2
    Collection col = malloc(sizeof(Collection)); is also wrong. Commented Sep 11, 2020 at 21:36
  • 1
    Collection is a typedef of struct collection *. So you are creating a variable of type struct collection * and pointing it to memory allocated to be the size of struct collection *. That is, you allocated the size of a pointer when you should have allocated the size of the object being pointed to. You can fix that by turning the malloc call into malloc(sizeof(*col)) Commented Sep 11, 2020 at 21:59

1 Answer 1

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++;
}
Sign up to request clarification or add additional context in comments.

2 Comments

sizeof(Collection) is the size of the pointer to the structure, correct?
@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.

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.