Reputation: 25703
Suppose I have a library compiled with compiler A. It allocates memory using malloc()
and leaves it to me to free()
it. It provides no special free function.
Can I compile my program (that uses this library) with compiler B? Or do I have to worry that one compiler's (standard library's) malloc
is incompatible with the other's free
?
In addition to the general question I would also like to know the answer specifically for these compilers: system clang on OS X with MacPorts' gcc 4.9 or 5.
Upvotes: 4
Views: 942
Reputation: 781096
It shouldn't be a problem. The operating system's ABI specifies how programs call library functions, and all programs and libraries are supposed to conform to this. This allows you to link programs created with different compilers together.
Your question indicates a confusion between compilers and libraries. Compiling a library with compiler A doesn't mean it uses Library A's malloc
function. Libraries are specified during the link step, not when compiling the library. When you create the executable program, you link the main program with the library you compiled and the C runtime library. malloc
and free
are provided in the C runtime library, and there will just be one of them in the resulting executable.
Upvotes: 4
Reputation: 25703
free
and malloc
are not always compatible between compilers. Specifically, they are not compatible between MSVC and MinGW.
I encountered the following situation:
I was using a C library that has a function that returns an array. The array must be free
d by the user when no longer needed. I was using a precompiled DLL of this library using MSVC. However, the DLL was compiled with MinGW. Using MSVC's free
on memory that was allocated with MinGW's malloc
causes a crash. But ensuring that free
/malloc
are always used in compatible pairs avoided the trouble, even if my program used a different C compiler than the DLL.
Upvotes: 3