Hello, everyone!
I have a problem with memory free. Here is the necessary code to understand the problem:
void fillArray(char** referenceArray, FILE* grid)
{
//Chaîne qui va contenir une ligne du fichier.
char* lineContent = malloc((width + 1) * sizeof(char)); //Pour contenir le "\0"
int i, j;
for (i = 0; i < height; ++i)
{
printf("Iteration nb %d\n", i);
referenceArray[i] = malloc(width * sizeof(char)); //Allocation de la mémoire pour une ligne du tableau.
fgets(lineContent, width + 1, grid); //width + 1 pour aller chercher "width" caractères.
printf("String: %s\n", lineContent);
for (j = 0; j < width; ++j)
{
referenceArray[i][j] = lineContent[j];
}
fgets(lineContent, 2, grid); //On se débarasse du "\n" au bout.
}
free(lineContent);
}
char** referenceArray;
char** newReferenceArray;
referenceArray = malloc(height * sizeof(char*));
fillArray(referenceArray, grid);
do
{
survivorCount = 0;
newReferenceArray = computeNextGen(&survivorCount);
printf("Survivor count: %d\n", survivorCount);
//TODO: Memory free problems!
for (i = 0; i < height; ++i)
{
free(referenceArray[i]);
}
free(referenceArray);
referenceArray = newReferenceArray;
++generationCount;
}
while (survivorCount != 0 && generationCount < generationLimit);
And here is the computeNextGen function.
char** computeNextGen(int* survivorCount)
{
int i = 0;
int j = 0;
char cellStatus;
char** arrayToReturn = malloc(height * sizeof(char));
for (i = 0; i < height; ++i)
{
arrayToReturn[i] = malloc(width * sizeof(char));
}
return arrayToReturn;
}
The problem happens at the iterations of the Life Game that follows the first one. Microsoft Visual Studio complains on runtime at the free(referenceArray) in the do-while loop. Looking at the code makes me blind for finding the mistake.
I hope that I have put enough code in my project to help you understand my problem. Putting a huge load of code is not very convenient for reading, I know...
Thank you for your help, if you know the solution.