I am new with C++. I use Visual Studio. My debug build works as intended, but the release build crashes with Access violation. The struct:
struct GeneticData
{
int NumberOfIdDataPairs;
char** IdBuffer;
char** DataBuffer;
};
IdBuffer is an array of char arrays of 20 chars, Databuffer is an array of chars array of 102 chars. The function which returns the pointer:
GeneticData* LoadData(FILE* dataFilePtr) //dataFilePtr is valid in the function
{
char* result = NULL;
int fileLine = 0;
GeneticData geneticData = *new GeneticData();
geneticData.NumberOfIdDataPairs = *new int;
geneticData.IdBuffer = new char*[gSizeOfBuffer];
geneticData.DataBuffer = new char*[gSizeOfBuffer];
for (int i = 0; i < gSizeOfBuffer; i++)
{
geneticData.IdBuffer[i] = new char[gSizeOfId];
geneticData.DataBuffer[i] = new char[gSizeOfData];
}
do
{
result = fgets(geneticData.IdBuffer[fileLine], gSizeOfId, dataFilePtr);
fgets(geneticData.DataBuffer[fileLine], gSizeOfData, dataFilePtr);
fileLine++;
} while (result != NULL && fileLine < gSizeOfBuffer);
if (result != NULL)
geneticData.NumberOfIdDataPairs = fileLine;
else
geneticData.NumberOfIdDataPairs = fileLine - 1;
return &geneticData;
}
The gSizeofBuffer is the number of id/data pairs, it's value is 1.000.000 at the moment. Inside the function everything is all right, I can acces the values of the id/dataBuffer. The issue arises in the function which calls my LoadData function.
GeneticData geneticData;
geneticData = *LoadData(dataFilePtr);
//acces violation, geneticData contained invalid values
With cout << geneticData.DataBuffer[1]
the debugger stopped here (post mortem debugging):
With cout << geneticData.DataBuffer[1][0]
the debugger stopped at this line. In the actual algorithm which analyses the content of DataBuffer the debugger stops like in the case of cout << geneticData.DataBuffer[1][0]
.
I allocated the memory of the GeneticData struct as dynamic memory, I do not understand why is the pointer invalid after the LoadData function returns it.