In a function I created am I trying to allocate a int array dynamically to store some index values.
First I create the int * with the malloc function and then let the loop store som values in it and increment the pointer each time. The problem I run in to starts when I try to use the realloc to increase the memory allocation.
When I do this VS tells me it runs in to undefined behaviour and breaks the program.
The code looks like this
void showAvailable(CabinHolder *holder, Booking *booking)
{
system("cls");
printf("Choose cabin number \n");
printf("Start week: &d \t End week: %d", booking->rentPeriod[0], booking->rentPeriod[1]);
printf("------------------------------------------\n");
int memory = 5;
int *indexOfCabin = (int *)malloc(sizeof(int)*memory);
int counter = 1;
for (int i = 0; i < CABINS; i++)
{
if (counter == memory)
{
memory *= 2;
int *expanded = realloc(indexOfCabin, (memory * sizeof(int)));
indexOfCabin = expanded;
expanded = NULL;
}
if (booking->cabin->typeOfCabin == holder->arrofCabin[i].typeOfCabin)
{
printf("%d. \t Cabin with number %d \t cost: %d per week\n", counter, holder->arrofCabin[i].nr, holder->arrofCabin[i].cost);
counter++;
indexOfCabin = &i;
indexOfCabin++;
}
}
free(indexOfCabin);
system("pause");
}
When I debugg in VS i also se that my pointer indexOfCabin seems to be undefined inside the if statement, which I don't understand. What have I missed here?