Prog 8
Prog 8
Memory
Overview
1. Multi-task And Memory Management
a. Issues ?
b. Virtual Memory
2. Processus Memory Organization
3. malloc(3)
a. Heap Management ?
b. A Simple First Fit Allocator
4. Other Kind Of Allocators
Multi-Task And Memory
Issues ?
Can we do better ?
Virtual Memory
Unmapped Other
Unmapped Current
…
Mapped Other
Mapped Current
…
Pages Translation Example
Intel ia32 (32bits) schema:
➢ We use 4KB pages (12bits)
➢ Pages are grouped in page directory
➢ Translation is done in two step:
1. Translate the page directory base address
2. Translate the page base address
➢ The page directory table contains 1024 entry of 4
bytes each pointing to page table of the same
size. A full mapping takes at most 4MB for 4GB.
Process Memory
Memory Organization
➢ Each process has its own address space
➢ The memory is divided in segments:
● Text Segment: the process image (code)
● Data Segment: static initialized variables
● BSS Segment: static uninitialized variables (fill with 0)
● Heap: where dynamic allocation should take place
● Memory Mapping Segment: mapped files, libs …
● Stack: process (main thread) stack
➢ The kernel is also mapped, in the higher part of
the memory.
Process Layout (Linux 32bits)
0
Text Segment
Data Segment
BSS Segment
3GB Heap
Stack
int tab[8];
break
page boundary
void *malloc(size_t s) {
void *r;
if ( (r = sbrk(s)) == (void*)(-1) )
return NULL;
return r;
}
Comments
Pros:
➢ Minimal cost (just the cost of sbrk(2))
➢ No waste space and no overhead
Cons:
➢ Can’t implement free(3)
➢ realloc(3) is unsafe
What Do We Need ?
We need meta-data !
Strategy
meta-data data
➢ size
➢ free
➢ next
size bytes
Pointer
returned
Structured Heap
struct chunk {
struct chunk *next; ➢ next is the list pointer
size_t size; ➢ we keep data size only
➢ free indicate chunk availability
int free;
➢ we may add information later
};
Construction Of malloc
free(p)
➢ First we need to verify p:
● it must be between the base of the heap and its end
● it must aligned on sizeof (void*)
➢ Then we must access the meta-data:
● they lie (sizeof (struct chunk)) bytes before p
● we just have to set the free field to 1
Valid call to free ?
meta meta
data
data data
k n-k-sizeof(chunk)
Fragmentation
meta meta
meta
data data data data data
data
(free) (free)
meta
data
data
Doing Better ?
index
Data