ofstream::open creates file, but then crashes (bad

2019-08-04 17:27发布

So I have some code that looks like this, written in and compiled with Visual Studio 2010:

if ( outputFile.is_open() )
{
    outputFile.close();
}
if ( !outputFile.is_open() ) // condition for sanity-checking
{
    outputFile.open("errorOut.txt", ios::out);
}

This crashes on an access violation. Attaching a debugger shows that the first condition is false (outputFile is not open), the second condition is true (outputFile is closed, which is good since I just checked it). Then open() gets called, and eventually locale::getloc() attempts to dereference a null pointer, but I have no idea why that would be happening (since that's now three classes deep into the Standard Library).

Interestingly, the file "errorOut.txt" does get created, even though the open call crashes.

I've spent a few hours watching this in a debugger, but I honestly have no idea what's going on. Anyone have any ideas for even trying to determine what's wrong with the code? It's entirely possible that some code elsewhere is contributing to this situation (inherited code), but there's a lot of it and I don't even know where to look. Everything up to that point seems fine.

1条回答
萌系小妹纸
2楼-- · 2019-08-04 18:00

OK, I'm not really sure if this is the best way to handle this, but since this involved some truly strange behavior (crashing in the middle of an STL function, and some other oddities like hanging on exit(1); and the like), I'll leave an explanation here for the future.

In our case, the error seemed to derive from some memory corruption going on in some truly awful code that we inherited. Cleaning up the code in general eliminated this crash and other strange behaviors displayed by the program.

I don't know if this will be useful to anyone; maybe it would have been better to simply delete the question. I'm actually somewhat curious if I should have, if anyone wants to leave a comment.

查看更多
登录 后发表回答