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 usingrealloc
inaddOrder
function has no effect ondata
variable inmain
function. You may need to passdata
using reference or return
updated value from function and assign it todata
.
4
solved Realloc to structure in c