Sign in to follow this  
Sfpiano

Strange memory leak error

Recommended Posts

maip.cpp
#include <fstream>
using namespace std;

ifstream inFile("file.txt");
if( inFile.bad() ) {
	inFile.close();
	return 0;
}
inFile.close();

CMolecule m;
m.createFromFile(string("file.txt"));
CMolecule.cpp
void CMolecule::createFromFile(string filename) {
int i;
char line[1024];

ifstream inFile;
inFile.open("file.txt");
if( inFile.bad() ) {
	inFile.close();
	return;
}
...
}
The program calls the createFromFile function fine, but bails out on inFile.open() (in CMol.cpp) saying: Unhandled exception: std::bad_alloc. I have no idea how that could work right before the call, but not after when nothing inbetween happened. [Edited by - Sfpiano on October 3, 2006 9:58:27 PM]

Share this post


Link to post
Share on other sites
If you're trying to do what I think you're trying to do, shouldn't your code:
Quote:
inFile.open("file.txt");
be something like:
inFile.open(filename);

However, I don't see how my correction could fix your code. I'd try doing a step-through of the inFile.open() method, see EXACTLY where it's crashing due to a BADALLOC.

Share this post


Link to post
Share on other sites
0) Is that your whole program? Cut out the rest of the program systematically until you find the problem. Simple file stream opening/closing *should* be perfectly robust, but if you corrupt the heap (or stack) somewhere, *anything* could fail later on.

1) Uh, aren't you including CMolecule.h in main.cpp or anything?

2) You rarely want to use .bad() explicitly to check a file. Just do if (stream instance). Streams have a useful boolean interpretation.

3) You don't need to explicitly create a std::string from a char* literal in order to call a function accepting std::string. That conversion is automatic (which is why conversion the other way isn't: automatic conversions both ways could cause unexpected ambiguities).

4) You ignore that string parameter anyway. I think what you wanted was "inFile.open(filename.c_str());" in the function.

5) But don't default-construct file objects and then .open() them. Just use the constructor that accepts a file name: "ifstream inFile(filename.c_str());" Why would you want the extra typing?

6) char line[1024]; makes me suspicious that you're going to do something nasty later on. You do know that you can read a line of text (with any delimiter you choose) directly into a std::string, yes? (std::getline(stream instance, destination string, [optional delimiter, defaulting to '\n']).)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this