user2593562
user2593562

Reputation: 116

Memory allocation in terms of paging

In terms of paging, how exactly does memory allocation work? I understand how the buddy allocator, free list algorithm, etc. all work, but in terms of virtual memory and paging I am confused. For example, lets say I malloc 10 bytes. Lets say that there are 10 4kb virtual pages available. The OS uses one of these pages to allocate the 10 bytes. Would the OS mark this page as "not free" now? I am sure it does not do that, but how does it keep track that there are (4kb - 10 bytes) left in that page?

Upvotes: 1

Views: 2886

Answers (1)

user1157391
user1157391

Reputation:

Linux only works with pages.

malloc is a C library function. It's job is to allow allocation of arbitrarily-sized blocks of memory. It acquires/grows/shrinks pools of pages by using the sbrk or mmap kernel's facilities. It keeps track of the allocated and free bytes in the pools.

If a page was used to allocate some memory that is later freed the kernel has no way of knowing it is no longer needed, unless malloc tells it to release it (e.g. via munmap).

When malloc requests a page from the kernel a free virtual page in the process's virtual address space is marked as valid and returned. Access to an invalid page triggers a segfault.

Usually allocation is lazy. It means that no real page (i.e. backing store) is allocated at first. The first time the process writes to this virtual page a real page is allocated and the virtual page is pointed to it.

Then this real page might move back and forth between physical memory and swap space as needed.

Upvotes: 4

Related Questions