what happens in the kernel during malloc?

后端 未结 2 380
深忆病人
深忆病人 2020-12-12 09:56

I was asked this question during an interview. What they wanted to know was when the user calls malloc(4) to allocate 4 bytes of memory how does the operating system (Linux)

2条回答
  •  温柔的废话
    2020-12-12 10:42

    There's a mistake in your answer - malloc does not deal with physical memory directly. It deals with paged virtual memory - although I'm not certain if it's true for every architecture out there.

    When your program tries to allocate memory and the free list doesn't contain a chunk of equal or larger size than the requested size, an entire new page is allocated. The page size is architecture dependent (4096 bytes on x86). Page allocation is something only the kernel can perform, thus a malloc call may cause a system call. The new address is then added to the free list, and malloc manipulates the free list according to its implemention (check glibc for example).

提交回复
热议问题