Tom Tom - 1 year ago 65
Linux Question

Linux and Mac has different C++ malloc() free()

Linux and Mac OS X has different C++ malloc() and free() implementation.
I have a source code compiled in MAC os X using GCC compilers.
It works fine, except it gives an error of

malloc: *** error for object 0x7fff77549d70: pointer being freed was not allocated*** set a breakpoint in malloc_error_break to debug`

When the same version of compiler is used to compile in linux (red hat) system, it compiles fine and runs fine.

So I suspect that there is something wrong with malloc() and free(). Is there any way to over write malloc and calloc on Mac OS X to that of Linux's so that I won't get this error?

I did not write the source code, so it is impossible for me to locate bugs and fix them.

Answer Source

To expand on my comment, free is defined to deallocate memory or to act as a no-op if the argument passed is NULL.

From my crystal ball, I therefore guess that you have code like:

Type *my_pointer;

// free anything I already have

// create something new
my_pointer = (Type *)malloc(sizeof(Type));

One compiler is happening to leave my_pointer initialised to NULL and the other isn't. The mistake, however, is yours, as the language states that my_pointer will have an undefined value. Just declare your expected initial value explicitly as Type *my_pointer = NULL;.