[Solved] Realloc to structure in c


You access out of bound for firma.

data = (Order*)malloc(ordersize * sizeof(Order));//we allocte memory for the struct Order with pointer data

add_orders(data, &ordersize); //send it

As you allocated memory of size orderSize and you access firma[newstart].

newstart = *ordersize; //we just did it
(*ordersize)++; // now we have new size +1 for the one more order

for (i = newstart; i < *ordersize; i++) //same as the input function but this one start and finish from the new start and finish
{
    printf("enter the ID of order number: %d\n", i + 1);
    scanf("%d", &firma[i].number);
    while (getchar() != '\n');

    .....
 }

Thus first allocate more memory and access.

   newstart = *ordersize; //we just did it
   (*ordersize)++; // now we have new size +1 for the one more order

    firma = (Order*)realloc(firma, (*ordersize * sizeof(Order))); //after we added the new order we do realloce for the new size for the struct
    if (!firma)//if failed
    {
        printf("error\n");
        return 0;
    }

   for (i = newstart; i < *ordersize; i++) //same as the input function but this one start and finish from the new start and finish
   {
       printf("enter the ID of order number: %d\n", i + 1);
       scanf("%d", &firma[i].number);
        while (getchar() != '\n');

       .....
   }

Note:: firma is local variable and allocating memory using realloc
in addOrder function has no effect on data variable in main
function. You may need to pass data using reference or return
updated value from function and assign it to data.

4

solved Realloc to structure in c