Hi, I'm curently creating a command line tool in VC++ 2008 Express Edition for myself which requires reading many files and merging them together. Everything is OK and during debugging (F5) there is not a single problem, but at run time (ctrl+F5) a problem with fread occurs at the same location each time. It reads many files without any problem and suddenly it stops at one file (each time the same one) and shows windows error dialog.

Document *load(string fileName){

	char *buffer;
	FILE *pFile;
	long lSize;
	size_t result;
	string strBuff;
	errno_t err;
	Document *document = new Document();

	err = fopen_s ( &pFile, fileName.c_str() , "rb" );
	strBuff = "Can't read file \""+fileName+"\"!";
	if (err) {fputs (strBuff.c_str(), stderr); exit (1);}
	if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

	// obtain file size:
	fseek (pFile , 0 , SEEK_END);
	lSize = ftell (pFile);
	rewind (pFile);

	// allocate memory to contain the whole file:
	buffer = (char*) malloc (sizeof(char)*(lSize+1));
	if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

	// copy the file into the buffer:
	result = fread (buffer,1,lSize,pFile);
	if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
	/* the whole file is now loaded in the memory buffer. */

	// Here occurs the error. File has been read, but buffer is clear, 
	// strBuff.assign crashes.
	free (buffer);
	// terminate
	fclose (pFile);
	return parse(strBuff, document);

As you can see from my code, all checks went ok, but for some reason, there is nothing in buffer. I've tried to find out maximal file size I'm going to read and it worked, but then the application is much slower (because of the conversion to string object). and it doesn't explain why it occurs. I would like to know, what is doing this error.

8 Years
Discussion Span
Last Post by Puliver

Have you tried replacing FILE with fstream and replace malloc()/free() with new/deleteo[] ? See example program here

Then, of course, replace fputs() with cout statements.


The assign(const char*) wants C-string terminated by zero byte. You forget to assign buffer[lsize] = '\0'; after fread. It's enough to raise erratical memory access error in assign.

Another notes:
1. No need to rewind pFile, use fseek again.
2. Think about exit() in C++ programs. Automatic objects destructors are not called when exit terminates a program. May be it's OK, may be not...
3. Avoid mixing of malloc/free and new/delete mechanics. Better use only new/delete operators in C++ programs.


Thank you, now I see it too. Most of the time I'm developing in other languages, so I forgot to add that '\0' at the end of string :). It works fine now, thanks. I've also changed malloc/free to new/delete.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.