memory allocation Flashcards
what is malloc used for
to get memory from the heap
what does malloc() return
a pointer to the start of the usable memory space (excluding meta data)
why do we use free() after using malloc()
the system can run out of space and there is no automatic garbage collection therefore we have to use free()
why should we not go outside the memory allocated via malloc()
because you will overwrite other data
usually the metadata for the rest of the allocatable space from malloc()
what are the four parts of the metadata in malloc()
whether the space is free
the length
prev and next pointers
what happens when we call free() (other spaces)
it coalesces all the free spaces around it
how does malloc create more efficient searching for different sizes of memory
similar size allocations are grouped together therefore you dont have to search the entire list
each section is usually in a different part of memory and is maintained with a doubly linked list
how is malloc usually implemented
a block of memory is added at the head of the free list like a stack
it maintains multiple free lists in different parts of memory
2 lists are used one being the actual block list and another that is explicitly free lists
what is the point of malloc using an actual memory block list and an explicit free memory block list
when scanning for space you dont have to look through the used blocks
what does each block tell us about the prev block and why
its length and whether its in use as it allows us to easily see whether we can coalesce it with the prev one
therefore when its updating its length and use status it also updates it in the next block
where is the used/free flag
in one bit from the length section
why do we have the length and used status as values rather than pointers
pointers require 8 bytes so this method requires less space
what happens when malloc runs out of memory
it calls sbrk(+/- value) which manages the top of the heap (that has a high water mark)
what do we call to read the high water mark of the heap
sbrk(0)
what happens when we call sbrk(positive value)
itll grow the heap and return the starting point of the extra memory
what happens when we call sbrk(negative value)
itll push down the heap thus passing memory back to the os
a page
a 4k block of memory that the system manages memory in
what do we use if we want multiple pages of memory
mmap(number of pages)
map-anonymous
using mmap but not linking to a file
unmap()
returns memory back to the os