Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code for malloc and free

Tags:

c

linux

malloc

free

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.

like image 254
MetallicPriest Avatar asked Jun 26 '11 17:06

MetallicPriest


People also ask

What does free () and malloc () do in C?

In the C programming language, two of the functions used to allocate and deallocate the memory during run-time are malloc() and free() , respectively.

How do you implement malloc and free?

The easiest way to do it is to keep a linked list of free block. In malloc , if the list is not empty, you search for a block large enough to satisfy the request and return it. If the list is empty or if no such block can be found, you call sbrk to allocate some memory from the operating system.

How do you free a malloc function?

To free() the allocated memory, you only need to pass the returned pointer from malloc() and family. free (presult); without any issues. It will carry out the intended job.

Does C++ use malloc and free?

new vs malloc() and free() vs delete in C++ We use new and delete operators in C++ to dynamically allocate memory whereas malloc() and free() functions are also used for the same purpose in C and C++.


2 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).

like image 111
Cédric Julien Avatar answered Sep 25 '22 11:09

Cédric Julien


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.

like image 36
wallyk Avatar answered Sep 25 '22 11:09

wallyk