Where can I find the code for malloc my gcc compiler is using at the moment? I actually want to write my own malloc function which will be a little different from the original one. I know I can use hooks et all, but I want to see the real code.
-
write malloc() , then got to definition. (F12 usually) – Yochai Timmer Jun 26 '11 at 17:42
-
I'm working in Linux and not using any debugger. I want to know the file where it is found. – MetallicPriest Jun 26 '11 at 17:44
-
Unless you're just doing this as a learning experience, it's a very very bad idea. Poking with redefining standard functions, especially something that's as core as malloc, results in fragile, non-portable code. – R.. GitHub STOP HELPING ICE Jun 26 '11 at 17:47
-
4Writing your own malloc doesn't mean you want to *redefine* it – Karoly Horvath Jun 26 '11 at 17:57
-
Actually what I want to achieve is that a process is a replica of another process and performs the same computations as the original process. Now the replica process wants to have memory allocated at same addresses as the original one, so I need to emulate malloc for the replica process and the original has to log some information to be used by the replica – MetallicPriest Jun 26 '11 at 19:51
3 Answers
The POSIX interface of malloc is defined here.
If you want to find out how the C library in GNU/Linux (glibc) implements malloc
, go and get the source code from http://ftp.gnu.org/gnu/glibc/ or browse the git repository and look at the malloc/malloc.c
file.
There is also the base documentation of the Memory Allocator by Doug Lea that describes the theory of a m(emory)alloc(ator) (read this carrefully, and then decide if you really need to implement your own malloc).

- 2,786
- 22
- 32

- 78,516
- 15
- 127
- 132
-
Note that the implementation links are for *specific* implementations. They are not universal. – Some programmer dude Jan 25 '22 at 11:09
Look in the appropriate release of glibc at the old release site1 or here. For example, if you are using glib 2.9, it is in this archive. Look for the file malloc/malloc.c
.
You will see that it is not a trivial piece of library code.
1 It looks like they changed the directory structure after glibc-2.9.

- 56,922
- 16
- 83
- 148
malloc()
should be in glibc.
Further Reading
Multithreading
C++ allocation tricks [Video]

- 24,552
- 19
- 101
- 135

- 94,607
- 11
- 117
- 176