Dynamic Memory Allocation
Heap
- Dynamic, hierarchical memory allocation
- Unlike stack, which is LIFO
- Much slower than stack
- Program must not end before freeing all memory from the heap. Otherwise, memory leak.
- Compiler will not complain
Memory Management
Use #include <stdlib.h>
Important
Remember to assert that the memory allocation was successful
int* myPtr = malloc(10 * sizeof(int));
assert(myPtr);
Malloc
/**
* Allocates block of memory of `size` number of bytes but doesn't initialize
*
* @returns a pointer to the first memory block
* @returns NULL, the null pointer, if there is insufficient memory or size == 0
*/
void *malloc (size_t size);
Note the void pointer, pointing to a memory location with nothing. We also don't define the type, it gets casted later.
Free
/**
* Frees a memory block that was allocated by user
* Failure to free memory that you have allocated is called a memory leak
*/
void free(void *);
Note the void pointer param. This means we can take any type of pointer.
Calloc
/**
* Allocates block of memory of `numElem * size` number of bytes and initializes them as 0
*
* @returns a pointer to the first memory block
* @returns NULL, the null pointer, if there is insufficient memory or size == 0
*/
void* calloc(size_t numElem, size_t size);
Realloc
/**
* Resizes block of memory `ptr` to `size` number of bytes
*
* @returns a pointer to the first memory block
* @returns NULL, the null pointer, if there is insufficient memory or size == 0
*/
void* realloc(void* ptr, size_t size);
NULL Pointer
Generally, include with stdlib.h
int *p = NULL;
Sometimes, you may see
int *p = 0;
int *p = (int *) 0
int *p = (void *) 0
Creating Dynamic Array
Note for Structs
struct flex_array {
int length ;
int a[]; // The array
};
// Flex array will be initialized with the array being empty