So what I try to do is to dynamically allocate memory for a structure. The structure looks like this:
typedef struct{
char name[N];
int dimToys;
TOY toys[N];
}CITY;
I read some input from a .txt file and copy it in my structure.
Then I have a function in which I would like to reallocate memory(and do some other irrelevant stuff) but my program works only when I use this function one single time. If I try to realloc the memory multiple times, then my program crashes.
It looks something like this:
void next_city(CITY** cityList, *dimCities, otherstuff){
(*dimCities)++;
*cityList = realloc(*cityList, (*dimCities) * sizeof(CITY*));
otherstuff...
}
I tried running the debugger and it crashes at the line with realloc, when I call the function for the second time. The call of the function in the main function looks like this:
cityList = malloc(sizeof(CITY*));
for(...){
...
next_city(&cityList, &dimCities, otherstuff);
}
I've already tried using a temporary variable for the reallocation and then copy it in my original cityList, but it doesn't work neither.
LATER EDIT:
Because a lot of people told me to update my question with some clarifications, I'll just show my code more clear, after I made some modifications from what you all told me.
void next_city(char line[], CITY **cityList, int *dimCities){
(*dimCities)++;
*cityList = realloc(*cityList, (*dimCities) * sizeof(CITY)); //UPDATE CITYLIST DIMENSION
cityList[(*dimCities) - 1]->dimToys = 0;
char *word = strtok(line, " ");
strcpy((cityList[(*dimCities) - 1]->name), word); //INSERET NAME OF THE CITY
word = strtok(NULL, " ");
strcpy((cityList[(*dimCities) - 1]->toys[cityList[(*dimCities) - 1]->dimToys].toyType), word); //INSERT NAME OF THE TOY
}
int main(){
int nrPasi;
int dimCities = 0;
scanf("%d", &nrPasi);
fgetc(stdin);
int i;
CITY *cityList;
cityList = NULL;
char line[100];
for(i = 0;i < nrPasi;i++){
fgets(line, 100, stdin);
next_city1(line, &cityList, &dimCities);
}
return 0;
}
So I basically read something like
3
Berlin car
Berlin doll
Madrid jacket
And I just want to read it step by step. After I switched CITY* with CITY now realloc doesn't break my program, but it happens on the next line, when I try to access it. I get SISGEV
*cityList = realloc(*cityList- This is bad form. What happens inreallocfailscityListinmain().N? You need to give an minimal reproducible examplecityListinmain, and anywhere you set*cityList) is present (and verify that you still see the problem).