Skip to the task
Layout
Back to classic view
READTask 1 of 20 · step 1: The heap, malloc and freeThe stack and the heap
The stack and the heap in practice/10/

Variables on the stack disappear with the function, a heap block lives until free. malloc and the NULL check, n * sizeof *p, free and p = NULL, who frees it is written in the contract.

Details & hint

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

stack (main)heap n = 10squares 149162536496481100 stack: gone when the function returnsheap: lives until you call free malloc(10 * sizeof *squares) = 40 bytes
  • 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, or NULL if it got none. The contents are garbage, like an uninitialised variable.
  • sizeof *squares is the size of one element. If you later change int to double, the line stays correct.
  • free(p) gives the block back. Afterwards p still points at that place, but it isn't yours any more: assign NULL. 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.

practice 10 CMakeLists.txt Code Diff
UNCHANGED This step does not change this file.
add_executable(p10_cities cities.c)