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/05/

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 05 recursion.c Code Diff
UNCHANGED This step does not change this file.
#include <assert.h>
#include <stdio.h>
/* The digit sum; depth is how many calls deep the function already is.
Before: n >= 0, depth >= 0.
After: the sum of the digits of n. */
int digit_sum(int n, int depth) {
assert(n >= 0 && depth >= 0);
printf("%*sdigit_sum(%d)\n", depth * 2, "", n);
if (n < 10) {
return n;
}
return n % 10 + digit_sum(n / 10, depth + 1);
}
/* n! = 1 * 2 * ... * n.
Before: n is from 0 to 20 (21! doesn't fit in a long long).
After: the factorial of n; 0! = 1. */
long long factorial(int n) {
assert(n >= 0 && n <= 20);
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
int main(void) {
int sum = digit_sum(472, 0);
printf("Digit sum: %d\n", sum);
printf("5! = %lld\n", factorial(5));
printf("20! = %lld\n", factorial(20));
return 0;
}