Re: malloc() fail
The Doctor wrote:
On Sun, 21 Sep 2008 12:08:34 +0000, Erik Wikstr??m wrote:
On 2008-09-21 13:02, The Doctor wrote:
Hey people,
I have a really weird problem.
I am developing a string class, just for fun. I am also writing an
application, which uses the string class, and uses a lot of them. But,
after about thirty String string = new String("blahblahblah"), I get
the following error:
*** glibc detected *** ./myapp: malloc(): memory corruption (fast):
It means you have a memory error, like e.g. writing past the end of an array
or trying to free a block of memory you already have freed, or calling free
with an address you didn't get from malloc.
0x080641f8 ***
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6[0xb7bea962]
/lib/tls/i686/cmov/libc.so.6(__libc_malloc+0x8d)[0xb7bebcad]
/usr/lib/libLCore.so(_ZN7StringC1EPKc+0x4b)[0xb7eeafff] ./ka[0x804d3e4]
./ka[0x804b72a]
./ka(__gxx_personality_v0+0x3f4)[0x804b244]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe0)[0xb7b94450]
The code where the app crashes:
String::String(const char* other)
{
/*
allocate space for the actual string data, the Data structure
contains an int, which contains the length of the string,
and a
pointer to a short array.
*/
d = (Data*)malloc(sizeof(Data));
/*
Allocate new data space, this is where the application crashes */
d->data = (short*)malloc(sizeof(short));
A typical problem of this kind of bug is that the program often doesn't
crash at the place where the actual error is. It's likely that the last
memory allocation or deallocation you did before this one broke the memory
manager's internal data. If you happen to be using linux/x86, you can try
using valgrind. It's a memory debugger that can tell you in which line of
your code the real error is.
I can't see anything wrong with the code so far, you need to post (at
least) the definition of Data (please see the FAQ on how to post a
question).
A question though, why use malloc and not new?
Data:
struct Data
{
int size;
short* data
};
That doesn't really help much.
Would new and delete[] have prevented this then?
Probably not.
It is impossible to post the whole code, since it is huge.
You sould rather reduce your program to the smallest complete program that
still contains the error. Chances are that you will find the error in the
process. If not, you can post that reduced version of the program.