Ok, this code is executes around 6 hundreds times at the start of the application, as it's related to a parser used by a group of classes when they are initialized.
FILE *file = fopen( str.c_str(), "r");
if( file )
{
// Go to the end of the file for getting file size;
fseek(file, 0, SEEK_END);
constlong fSize = ftell(file);
// Go back to the start;
rewind(file);
// Read on the buffer;
char *buffer = newchar[fSize];
printf("\nRead file into buffer");
fread(buffer, 1, fSize, file);
// Store the buffer on the content string;
printf("\nfileContent");
fileContent = buffer;
// Clean buffer from memory;
printf("\nDeleteBuffer");
delete[] buffer;
fclose(file);
file = 0;
}
I’m really curious to understand why the application crashed with this code! I’m coding with visual studio 2k8 pro (using Windows XP SP3, OSG, PhysX and OpenAL) and when running in release mode from the IDE we have no problem, but when running from the executable the application crashed always after running around one hundred times.
Changing this code by the streams one above solve the problem, I guess what’s really getting me nervous is not understanding at all why the error is happening!
Unless I'm mistaken, I'm assuming that fileContent is a string. In that context, I would guess that buffer is not null-terminated. You could add an additional char to the size of the buffer and set it to 0 after calling fread. Even better, use the string's constructor that takes a size:
fileContent = string( buffer, fSize );
At least one of fstream::rdbuf() or stringstream::str() must be null-terminated.
Haaaaaa! Nice!!! It really worked smooth with your suggested code:
fileContent = string( buffer, fSize );
Yes, the fileContent is an std::string : )
Thansk a lot for the fast reply. Any idea why the error didn’t appear when running the application from inside the IDE? Or why the code hasn’t thrown any error several times, before crashing?