Re: Segfault on ofstream::open
Dave wrote:
I have some code to write an object to a file, and I am getting a
segfault from within the C++ libs that I can't figure out. The file-
writing code is below.
void SystemConfig::Write(const std::string& filename) const
{
std::ofstream fout;
std::string fnc = filename.c_str();
Why this? It forces a copy of 'filename'. Anyhow, it still depends
on 'filename' being a valid object.
fout.open(fnc.c_str());
What is the content of 'fnc' at this place?
BTW:
std::ofstream out(filename.c_str());
Initialise and open in one step.
I added cout lines so that I can track down the exact line of the
segfault, and it is coming from the fout.open() call.
There are only three reasons for that:
1. The implementation is wrong, i.e. the ofstream implementation contains a
bug.
2. The call is wrong, i.e. you are giving an invalid string to the open()
function. That would be pretty hard, since std::string already makes sure
that its internals are valid.
3. Some other corruption caused the system to fail.
My first thought was that filename was bogus, but if I print it out,
I get what I expect. And besides, I am making a copy of it above, so
it should be legit.
I would lean towards reason #3. Note that the corruption can be anywhere, it
is just coincidence that it surfaces at that place. E.g. a corrupt heap
only surfaces when you actually use it, which can be much later than the
curruption.
One thing that seems relevant. This code works most of the time. It
seems to segfault when the program is exiting and dumping its config
to file. So, it occurs to me that maybe some important static data has
already been toasted before my function gets called. If so, how can I
tell if it's safe to write out the file or not?
Ew, that would be the reverse variant of the static initialisation order
fiasco. What I would do is to not write the configuration at all. Rather,
only write it while the program is running after it was changed. If
absolutely necessary, write it right before leaving main(), i.e. before
cleanup is started but don't write it from inside the destructor of a
global/static object.
Uli
--
Sator Laser GmbH
Gesch??ftsf??hrer: Thorsten F??cking, Amtsgericht Hamburg HR B62 932
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]