3

I'm learning about malloc and understand what it's used for. I'm curious if malloc is written in C. If so, I'd like to see the code that defines it. Anyone know where I can find the definition of malloc?

EDIT:

I'm aware of this link (and many like it on google) http://pubs.opengroup.org/onlinepubs/009695399/functions/malloc.html but that's not the code definition of malloc. I'm looking for the source file (if it exists) where malloc is defined. Something that looks like this

void *malloc(size_t size) {
   // code for how malloc is implemented
}
User314159
  • 7,733
  • 9
  • 39
  • 63
  • Read this: http://web.eecs.utk.edu/~huangj/cs360/360/notes/Malloc1/lecture.html – Rahul Tripathi May 18 '16 at 08:02
  • there are many implementations, search for `doug lea malloc` as its the most popular – george_ptr May 18 '16 at 08:02
  • Check `glibc` shource code. – Sourav Ghosh May 18 '16 at 08:03
  • 1
    If you want to understand memory allocators you should not attempt to read the source for an existing optimized system allocator. Instead I suggest you try to find out resources on how memory allocators work generally, learn the basics of memory allocators, and then step by step learn more about more advanced allocators until you can understand what your system allocator does. Or don't bother at all, and just know that "it works" and be happy with that. – Some programmer dude May 18 '16 at 08:07

4 Answers4

3

I recommend you to check the GNU C library: glibc.

http://www.gnu.org/software/libc/download.html

You can read the code there. In the malloc folder.

2

malloc() is defined in Standard Library, as far as all unix flavors are concerned, and probably more, since Standard Library belongs to the C library. Whichever system has a C library and C API implemented, one could at least expect it to have a malloc.

Here are few more (beside above mentioned GNU) links with source code:

NET BSD malloc
OSX malloc

Some legacy unix systems (IRIX for example), beside having Standard Library malloc() also used to have a fast libmalloc implementation.

Please, also take a look at this SO post.

Community
  • 1
  • 1
user3078414
  • 1,942
  • 2
  • 16
  • 24
1

Code for malloc and free

https://code.woboq.org/userspace/glibc/malloc/malloc.c.html

https://fossies.org/dox/glibc-2.23/malloc_8c_source.html

Above are link for code of malloc.

Community
  • 1
  • 1
Nikesh Joshi
  • 824
  • 6
  • 17
0

http://pubs.opengroup.org/onlinepubs/009695399/functions/malloc.html You can find many of such definitions. You should try to google it first :)