Subha wrote:
Hi All,
I'm facing a problem with malloc. I have a program which opens a file
to write something using ofstream.
I used to run more than a process same time and in that case one of the
process get stucked in malloc.
ofstream* _file ;
_file = NULL ;
You should combine the two statements to
ofstream* _file = NULL;
That way it's harder to inadvertently remove the assignment of NULL and
leave you with an uninitialized pointer. (This is just a style thing,
not the cause of your problem.)
>
if(access("filename", 0) == 0)
{
cout << "File already exists" ;
return ;
}
_file = new ofstream("filename", ios::trunc) ;
And if the code you're showing is really a good representative, just
move the declaration of _file to here:
ofstream* _file = new ofstream(...);
This does a couple things. One, it moves the declaration closer to the
use, which (IMO) makes understanding easier because it limits the
scope. Two, you never have an invalid _file pointer at all. (Again,
just a style thing.)
For that matter, why not create _file on the stack? (There could easily
be a reason why you don't, but even in that case consider a smart
pointer of some variety.) This would probably fix the problem you're
having right now, but something else would almost certainly break
sooner or later.
if(!_file->good)
{
stderr("Error in file open") ;
}
The process get stucked during the "new ofstream".
I'm working in unix. I tried mcheck/mtrace and many other, but still
can;t solve it.
The process stack is:
Thread 1 (Thread 182905645888 (LWP 29543)):
#0 0x0000002a95d91713 in _int_malloc () from /lib64/tls/libc.so.6
#1 0x0000002a95d905d2 in malloc () from /lib64/tls/libc.so.6
#2 0x0000002a95a54da5 in operator new () from
/usr/lib64/libstdc++.so.5
#3 0x0000000000436305 in MyFile::openFile ()
Can anybody help in this regard?
But to answer your question... it's probably a heap corruption issue. I
don't see anything wrong with the code you presented, and even if there
was there should essentially never be a crash when calling new.
So there's probably an out-of-bounds reference in a heap-allocated
array, a use of an uninitialized pointer, something like that which is
causing your heap to go bad. There are programs that can help you find
errors like this, such as I think Purify and Valgrind, though my
experience is sorely lacking exposure to these tools so I can't testify
to them being able to do exactly what you want.
Evan
>
Thanks,
Subha