

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 3
click for more info
Not enough gems
Cost: 6 gems
1: The Stack
incomplete
2: Why a Stack?
incomplete
3: Stack Overflow
incomplete
4: Pointers to the Stack
incomplete
5: The Heap
incomplete
6: Malloc
incomplete
7: Free
incomplete
8: Big Endian and Little Endian
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
The free function deallocates memory that was previously allocated by malloc, calloc, or realloc.
int *ptr = malloc(4 * sizeof(int));
free(ptr);
IMPORTANT: free does not change the value stored in the memory, and it doesn't even change the address stored in the pointer. Instead, it simply informs the operating system that the memory can be used again.
Forgetting to call free leads to a memory leak. This means that the allocated memory remains occupied and cannot be reused, even though the program no longer needs it. Over time, if a program continues to allocate memory without freeing it, the program may run out of memory and crash.
Memory leaks are one of the most common bugs in C programs, and they can be difficult to track down because the memory is still allocated and accessible, even though it is no longer needed.
We may be inefficient here at Sneklang, but we don't want outright memory leaks!
See how it's calling the allocate_scalar_list function in a loop? Well, the lists aren't needed from loop to loop, so they should be freed at the end of each iteration. If we do that, we should be able to allocate as many lists as we want (because we return the memory in between iterations).