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

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 02 main.c Code Diff
UNCHANGED This step does not change this file.
#include <limits.h>
#include <stdio.h>
#include "input.h"
int main(void) {
const int current_year = 2026;
int study_year = 1;
char group = 'A';
int birth_year = read_int("Year of birth: ");
int g1 = read_int("Grade 1: ");
int g2 = read_int("Grade 2: ");
int g3 = read_int("Grade 3: ");
double average = (g1 + g2 + g3) / 3.0;
int age = current_year - birth_year;
printf("Year of study: %d\n", study_year);
printf("Group: PI25%c\n", group);
printf("Age: %d years\n", age);
printf("Average: %.2f\n", average);
printf("In memory: int %zu B, double %zu B, char %zu B\n", sizeof study_year, sizeof average,
sizeof group);
printf("\n");
printf("Largest int: %d\n", INT_MAX);
long long century = 100LL * 365 * 24 * 60 * 60;
printf("100 years: %lld s\n", century);
printf("0.1 + 0.2 = %.17f\n", 0.1 + 0.2);
return 0;
}