Dynamic Memory Allocation

Heap

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

Creating Dynamic Array

Dynamic Arrays

Using Dynamic Memory Allocation,

Example

int *numbers(int n) {
    int *p = malloc(n * sizeof(int));

    assert(p); // Verify that malloc succeeded

    for (int i = 0; i < n; i++) {
        p[i] = i;
    }

    return p;
}

// Deleting
int main() {
    int *arr = malloc(5 * sizeof(int))

    assert(arr);
    free(arr);
}

Note for Structs

struct flex_array {  
    int length ;  
    int a[]; // The array 
};

// Flex array will be initialized with the array being empty