first layer:
sometimes run out of space on heap, need more. need to tell OS that more virtual memory is needed — ask OS for more virtual memory using brk() (‘please extend the heap’). mmap() (‘create new virtual region in the address space’) is a generalised brk(). munmap() is undo for mmap().
every time you need memory, the mmu will try to translate and get page fault, which is done with page fault handler.
virtual memory regions are basically contract between OS and application on legal ranges of memory that we can access
demand paging:
Program calls brk() to grow its heap
brk() enlarges virtual memory address space. new pages are not mapped onto physical memory.
Program tries to access new memory, processor page faults.
Kernel assigns page frame to process, creates page table entry, and resumes execution. Program lives happily ever after in userland.
allocate user space allocator. gets memory from kernel, divides that, etc.
void *malloc(size_t size)
— allocate size bytes. alignment should be 8 bytes.void free(void *ptr)
— free object starting at ptrvoid *calloc(size_t nmemb, size_t size)
— allocate nmem * size bytes, zeroed outvoid *realloc(void *ptr, size_t size)
— grow object starting at ptr to size bytes, optionally moving allocation if needed.requesting memory from kernel
int brk(void *addr)
— set program break (end of heap) to addr (if reasonable)void *sbrk(intptr_t increment)
— grow/shrink heap by increment bytes. returns old brk address.getting started
void *mymalloc(size_t size) {
return sbrk(size);
}
problems:
design options
in-band list metadata
each node contains metadata (size, next, prev, is_free) and space for the object.
when freeing, merge with adjacent free areas. avoid fragmentation — non-contiguous free areas.
list metadata example
struct obj_metadata {
size_t size;
struct obj_metadata *next;
struct obj_metadata *prev;
int is_free;
};
don’t use artificial limit on max number of objects. should have pointer to heap_start, and pointer to freelist (both void). dynamically grow. would give penalty.
Grading