Search code examples
cdynamic-memory-allocationdynamic-arraysrealloc

Why do I get realloc(): invalid next size?


I am trying to add elements to a dynamic array of structures in a function. Everything seems to be correct and when I add the first element it actually succeeds but when I try to add another I get:

realloc(): invalid next size

I tried to debug it in many ways, checking if all of the values are correct - the current size, the allocated memory and so on and everything is as it should be. I even did it "manually" (without a function) and it worked as it is supposed to work but when I do it with the function it fails. Is there a mistake I have made in my code which I do not see or am I missing something about allocating dynamic memory?

Here is the code:

typedef struct Product_t {
    char name[100];
    int price;
    int id;
} Product;

void add_product(Product** products, Product product, int *size) {
    (*size) += 1;
    
    if(realloc((*products), (*size) * sizeof(Product)) == NULL)
        exit(1);
        
    (*products)[*size - 1] = product;
}

int main() {

    Product* products = (Product*) malloc(0);
    int products_size = 0;
    
    Product p1 = {"product1", 45, 1};
    Product p2 = {"product2", 212, 2};
    Product p3 = {"product3", 123, 3};
    
    add_product(&products, p1, &products_size);
    add_product(&products, p2, &products_size);
    add_product(&products, p3, &products_size);
    
    return 0;
}

P.S. I know it would be better to do this with a linked list for example but I am required to do it with a dynamic array.


Solution

  • Address pointed by the pointer passed to the realloc is not guaranteed to remain the same, per man page of the realloc. So you need always assign the return value of realloc(...) to (*products) unless it is NULL.