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.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios
  5. 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 n values of type int. What is wrong?

    ```c
    int *t = malloc(n);
    `

    • It reserves n bytes: it needs n * sizeof(int)
    • The (int *) cast in front of malloc is missing
    • The pointer t should be declared as char *
    • It must go through calloc, malloc is only for strings
    Show the answer

    It reserves n bytes: it needs n * sizeof(int)

    malloc counts in bytes. With 4 bytes per int, n bytes hold only n / 4 integers: writing the rest overflows the block. In C, casting the result of malloc is unnecessary, because a void * converts implicitly.

  • Blocks obtained with malloc live on the …, whereas a function's local variables live on the ….

    Show the answer

    Blocks obtained with malloc live 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 free

    Slow, 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.