Skip to content
Advertisement

About memory allocation, does C malloc/calloc depends on Linux mmap/malloc or the opposite?

As far as I know, C has the following functions, e.g: malloc, calloc, realloc, to allocate memory. And the linux kernel also has the following functions, e.g: malloc, mmap, kmalloc, vmalloc… to allocate memory.

I want to know which is the lowest function. If you say, “Linux kernel is the lowest function, your C program must allocate memory with Linux kernel”, then how does the Linux kernel allocate it’s own memory?

Or if you say, “Linux kernel is the lowest function.”, then when I write a C program and run in the Linux system, to allocate memory, I should through the system call.

Hope to have an answer.

Advertisement

Answer

I want to know which is the lowest function.

The user-level malloc function calls brk or malloc (depending on the library used and depending on the Linux version).

… how does the Linux kernel allocate it’s own memory?

On a system without MMU this is easy:

Let’s say we have system with 8 MB RAM and we know that the address of the RAM is 0x20000000 to 0x20800000.

The kernel contains an array that contains information about which pages are in use. Let’s say the size of a “page” is 0x1000 (this is the page size in x86 systems with MMU).

In old Linux versions the array was named mem_map. Each element in the array corresponds to one memory “page”. It is zero if the page is free.

When the system is started, the kernel itself initializes this array (writes the initial values in the array).

If the kernel needs one page of memory, it searches for an element in the array whose value is 0. Let’s say mem_map[0x123] is 0. The kernel now sets mem_map[0x123]=1;. mem_map[0x123] corresponds to the address 0x20123000, so the kernel “allocated” some memory at address 0x20123000.

If the kernel wants to “free” some memory at address 0x20234000, it simply sets mem_map[0x234]=0;.

On a system with MMU, it is a bit more complicated but the principle is the same.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement