Dynamic Memory

Stack and Global Memory

Stack

  • One stack frame per function call

  • Local variables live there

  • Lifetime is the duration of the function call

Global memory

  • Global Variables

  • “Allocated” at program start

  • Lifetime: entire program

What’s in between?explicit lifetime

Dynamic Memory

Heap memory

  • Not part of the core language

  • ⟶ implemented in the C library

  • Lifetime is managed by the programmer

    • Allocation

    • Deallocation

  • See manual page

#include <stdlib.h>

void *malloc(size_t size);
void free(void *ptr);

Dynamic Memory - Usage

struct point *p = malloc(sizeof(struct point));
do_something_with(p);
...
free(p);

New traps: as always, there is no checking done (as always, this is for performance reasons)

  • Memory leak: forget to free() allocated memory

  • free() a pointer that does not point to dynamically allocated memory

  • free() a pointer that has already been deallocated