Lecture 7: Stack and Heap

We will now delve deeper into memory and the subdivisions of memory.

sections of memory

Stack

Limitations


Heap

To solve the limitations of the stack, we introduce a new section of memory called the heap which allows us to dynamically allocate memory manually.

Heap: The heap is a part of memory that you can manage yourself via dynamic memory allocation.
Dynamic memory: memory that can be allocated, resized, and freed during program runtime (while the program is running).

Heap Allocation

malloc

The main command/function to allocate memory on the heap is malloc:

void *malloc(size_t size); 

assert

Important:

assert(): a function that takes in a condition and terminates the program if the condition is false. This should be placed after every malloc call.

Example:

int *arr = malloc(sizeof(int) * len);
assert(arr != NULL); // if = NULL, terminate immediately 

calloc

To help with this there is also another command to allocate memory called calloc:

void *calloc(size_t nmemb, size_t size);

The following uses of malloc and calloc are equivalent:

// allocate and zero 20 ints
int *scores = calloc(20, sizeof(int));

// alternate (but slower, more lines of code)
int *scores = malloc(20 * sizeof(int));
for (int i = 0; i < 20; i++) scores[i] = 0; // zero out the bytes

strdup

Indeed, there is another command for allocation called strdup. This is useful for strings. Instead of having to copy the characters into the dynamically allocated array, C has a nice function:

char *strdup(char *s); // function signature, must take in char * 
strdup: a convenience function that returns a null-terminated, heap allocated string with the provided text, instead of you having to malloc and copy in the string yourself.
char *str = strdup("Hello, world!");

Freeing Memory

We must clean up after ourselves since we are dynamically allocating memory (there is no auto-delete memory like in the stack).

free: We delete memory using free by passing in the starting address on the heap for the memory you no longer need.
void free(void *ptr);

Example:

char *bytes = malloc(4); 
free(bytes); 

Some notes:

Memory leak

Memory leak: when you allocate memory on the heap, but do not free it (and lose the pointer to it?).

Realloc

We can use realloc to update the size of a dynamically allocated array.