Beruflich Dokumente
Kultur Dokumente
Lecture 10:
Dynamic Memory Allocation 1:
Into the jaws of malloc()
Dynamically-allocated
memory (via malloc) heap
Free byte
Allocated block Free block
(4 bytes) (3 bytes) Allocated byte
Program can allocate and free blocks of memory within the heap.
p2 = malloc(5)
p3 = malloc(6)
free(p2)
p4 = malloc(2)
Example:
● 5,000 malloc calls and 5,000 free calls in 10 seconds
● Throughput is 1,000 operations/second.
Examples of waste...
● Extra metadata or internal structures used by the allocator itself
(example: Keeping track of where free memory is located)
● Chunks of heap memory that are unallocated (fragments)
Heap
We define memory utilization as...
● The total amount of memory allocated to the
application divided by the total heap size Allocated
memory
Metadata
Internal fragmentation
● Internal fragmentation is the difference between the block size
and the payload size.
block
Internal Internal
fragmentation payload fragmentation
p1 = malloc(4)
p2 = malloc(5)
p3 = malloc(6)
free(p2)
p4 = malloc(6)
oops! - no free block large enough.
p = malloc(4) p
data
free(p) header
(address p-1)
a = 1: block is allocated
a size a = 0: block is free
size: block size
payload payload: application data
or free space
optional
padding
payload
5 4 6 2
Free Allocated Free Allocated
5 4 6 2
Free Allocated Free Allocated
Traverse each block until (a) we find a free block and (b) the block is
large enough to handle the request.
100
3 8 89
3 5 3 4 6
2 4 6 2
addblock(p, 4)
2 4 4 2 2
4 4 4 2 2
free(p) p
4 4 4 2 2
malloc(5)
Oops!
There is enough free space, but the allocator won’t be able to find it!
4 4 4 2 2
free(p) p
4 4 6 2
Header a size
a = 1: block is allocated
a = 0: block is free
“Pointers” in headers
4 4 4 4 6 6 4 4
“Pointers” in footers
m1 1 m1 1
m1 1 m1 1
n 1 n 0
n 1 n 0
m2 1 m2 1
m2 1 m2 1
m1 1 m1 1
m1 1 m1 1
n 1 n+m2 0
n 1
m2 0
m2 0 n+m2 0
m1 0 n+m1 0
m1 0
n 1
n 1 n+m1 0
m2 1 m2 1
m2 1 m2 1
m1 0 n+m1+m2 0
m1 0
n 1
n 1
m2 0
m2 0 n+m1+m2 0
Coalescing policy:
● Immediate coalescing: Coalesce each time free is called
● Deferred coalescing: Improve free performance by deferring coalescing until needed.
● Examples:
● Coalesce while scanning the free list for malloc()
p = malloc(sizeof(struct mystruct));
foo = (struct mystruct *)p;
p1 = malloc(4)
padding
p2 = malloc(5)