Memory allocation
A process's memory regions, static, automatic and dynamic allocation, malloc, calloc, realloc, free and sizeof in C, and the four classic faults: leak, double free, use after free and buffer overflow.
- 26 cards
- 5 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
- Understand
A few cards from the deck
Process memory layout: what is it?
Show the answer
The split of a program's address space into regions: the code, the data (globals and statics), the heap and the stack.
Each region sets its own lifetime: a global or static datum lasts the whole run, a stack variable lasts its function's call, a heap block lasts until its
free.This code is meant to store
nvalues of typeint. What is wrong?
```c
int *t = malloc(n);`- It reserves
nbytes: it needsn * sizeof(int) - The
(int *)cast in front ofmallocis missing - The pointer
tshould be declared aschar * - It must go through
calloc,mallocis only for strings
Show the answer
It reserves
nbytes: it needsn * sizeof(int)malloccounts in bytes. With 4 bytes perint,nbytes hold onlyn / 4integers: writing the rest overflows the block. In C, casting the result ofmallocis unnecessary, because avoid *converts implicitly.- It reserves
Blocks obtained with
malloclive on the …, whereas a function's local variables live on the ….Show the answer
Blocks obtained with
malloclive on the heap, whereas a function's local variables live on the stack.The stack empties by itself when the function returns; the heap only empties through explicit calls to
free.Dynamic allocation: what is it?
Show the answer
Reserving a block of memory while the program runs, whose size may depend on data known only at that moment.
The block comes from the heap and stays yours until you give it back with
free: neither the end of a function nor of a block gives it back.A server written in C sees its memory use climb by a few kilobytes with every request, never going back down, until it is killed. What is the most likely cause?
- The stack overflows because the requests pile up too quickly on top of one another
- Global variables are copied again with every request
- The compiler miscalculated the size of the local variables
- A block allocated per request is never given back with
free
Show the answer
A block allocated per request is never given back with
freeSlow, steady heap growth is the signature of a leak. A stack overflow happens all at once, through recursion or a big local array, not request after request.