Professional Documents
Culture Documents
Prog 6
Prog 6
The C Language :
Dynamic Memory
Allocation
David Bouchet
david.bouchet.epita@gmail.com
1
Static Allocations
file.
● The allocation is done when the program is
program.
● Usually used for global variables and literals.
2
Dynamic Allocations
3
Stack Allocations
● Fast allocation.
● Safe.
● No memory fragmentation.
● Local access.
4
Heap Allocations
● Slow allocation.
● Unsafe.
● Memory fragmentation.
● Global access.
5
Stack Allocation – Example
6
Heap Allocation – Functions
#include <stdlib.h>
Allocation
void *malloc(size_t size);
void *calloc(size_t nmemb, size_t size);
void *realloc(void *ptr, size_t size);
Deallocation
void free(void *ptr);
*p = 72
8
Dynamic Arrays - malloc()
malloc():
malloc() the memory is not initialized.
9
Dynamic Arrays - calloc()
calloc():
calloc() the memory is set to zero.
10
Dynamic Strings – malloc() (1)
11
Dynamic Strings – malloc() (2)
Hello World!
Good bye!
12
Dynamic Strings – realloc() (1)
13
Dynamic Strings – realloc() (2)
Hello World!
Good bye!
14
Dynamic Strings – Pointers to Pointers (1)
15
Dynamic Strings – Pointers to Pointers (2)
Hello World!
Good bye!
16