Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't I get a link error when I provide my own malloc and free?

Tags:

c

libc

I'm trying to implement a simple fit first memory management algorithm. So I've got a C file with my own

   void* malloc(size_t)

and

   void free(void*)

When generating a .out file with gcc, I'm expecting a link error because it'll conflict with the existing standard implementation. But my file links fine.

Please help me to understand.

like image 678
lang2 Avatar asked Jun 10 '13 09:06

lang2


1 Answers

I'm expecting a link error because it'll conflict with the existing standard implementation.

Your expectation is incorrect: most UNIX libc implementations support using some other malloc. To that end, they put malloc, realloc, free etc. either into a separate object file, or each into an object file of its own.

The linker is then free to replace malloc.o in libc.a with your implementation. You can read about the algorithm the linker uses here. Once you understand the algorithm, it should be clear why linking your own malloc and free does not cause a link error.

UNIX shared libraries are explicitly designed to emulate archive libraries, so while details of why you don't get a link error when linking with libc.so are different, the spirit is the same.

However, you aren't done. Linking any moderately complicated program with your implementation will likely crash, because when you replace malloc, you also need to implement realloc, and likely calloc and memalign and posix_memalign. Otherwise, you'll get a mixture of implementations, and when someone passes realloced pointer to your free, things will likely explode.

like image 145
Employed Russian Avatar answered Nov 17 '22 07:11

Employed Russian