Home > Mobile >  About memory allocation, do C malloc/calloc depend on Linux mmap/malloc or the opposite?
About memory allocation, do C malloc/calloc depend on Linux mmap/malloc or the opposite?

Time:03-20

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 throw the system call.

Hope to have an answer.

CodePudding user response:

On the linux OS, the C functions malloc, calloc, realloc used by user mode programs are implemented in the C library and handle pages of memory mapped in the process address space using the mmap system call. mmap associates pages of virtual memory with addresses in the process address space. When the process then accesses these addresses, actual RAM is mapped by the kernel to this virtual space. Not every call to malloc maps memory pages, only those for which not enough space was already requested from the system.

In the kernel space, a similar process takes place but the caller can require that the RAM be mapped immediately.

CodePudding user response:

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.

  • Related