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
|
#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 memoryfree()
a pointer that does not point to dynamically allocated memoryfree()
a pointer that has already been deallocated