Creazy Behavior

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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);
	const long fSize = ftell(file);


	// Go back to the start;
	rewind(file);

	// Read on the buffer;
	char *buffer = new char[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!

1
2
3
4
5
6
ifstream ifs( str.c_str() );

stringstream oss;
oss << ifs.rdbuf();

fileContent = oss.str();


I would really appreciate if anyone knows some explanation and thanks for reading it : )
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.
Last edited on
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?
Just blind luck, I guess. Everything would work out fine if the next byte in memory just happened to be zero.
Topic archived. No new replies allowed.