Theory
The heap, malloc and free
Until now the size of every array was known at compile time: Student s[MAX_STUDENTS]. The eleventh student doesn't fit, and with three of them 7 places are empty. Dynamic memory is allocated at run time, as much as needed.
The stack and the heap
- The stack – a function's variables. They appear when the function is called and vanish when it returns. Their size is known at compile time.
- The heap – memory the program asks for while running. It lives until the program gives it back.
malloc and free
#include <stdlib.h>
size_t n = 10;
int *squares = malloc(n * sizeof *squares);
if (squares == NULL) {
printf("Out of memory.\n");
return EXIT_FAILURE;
}
/* squares[0] ... squares[n - 1] */
free(squares);
squares = NULL;
malloc(bytes)returns a pointer to a new block of memory, orNULLif it got none. The contents are garbage, like an uninitialised variable.sizeof *squaresis the size of one element. If you later changeinttodouble, the line stays correct.free(p)gives the block back. Afterwardspstill points at that place, but it isn't yours any more: assignNULL.free(NULL)does nothing – that's allowed.
Who frees it?
Every malloc has exactly one free. When a function returns new memory, say in its contract that the caller frees it:
/* Returns a new copy of s in dynamic memory, or NULL if there isn't enough.
Before: s != NULL. After: the caller frees the copy with free. */
char *copy_string(const char *s);
Memory that is never freed is a leak: over time the program eats more and more memory.