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 cities.c Code Diff
UNCHANGED This step does not change this file.
#include <assert.h>
#include <stdio.h>
#include <string.h>
#define MAX_NAME 20
#define CITY_COUNT 5
/* City: three pieces of data of different types under one name. */
typedef struct {
char name[MAX_NAME];
int population;
double area; /* km2 */
} City;
/* Prints one city. Before: c != NULL. */
void print_city(const City *c) {
assert(c != NULL);
printf("%s: %d people, %.1f km2\n", c->name, c->population, c->area);
}
/* Gets a COPY of the city: the original doesn't change. */
void grow_copy(City c, int count) {
c.population += count;
}
/* Gets a pointer to the city: changes the original. Before: c != NULL. */
void grow(City *c, int count) {
assert(c != NULL);
c->population += count;
}
/* Population density, people per km2. Before: c != NULL, c->area > 0. */
double density(const City *c) {
assert(c != NULL && c->area > 0);
return c->population / c->area;
}
/* The index of the city with this name, or -1.
Before: n >= 0, t and name not NULL. */
int find_city(const City t[], int n, const char *name) {
assert(n >= 0 && t != NULL && name != NULL);
for (int i = 0; i < n; i++) {
if (strcmp(t[i].name, name) == 0) {
return i;
}
}
return -1;
}
/* Sorts by population, largest first, by selection.
Before: n >= 0, t != NULL. */
void sort_by_population(City t[], int n) {
assert(n >= 0 && t != NULL);
for (int i = 0; i < n - 1; i++) {
int max = i;
for (int j = i + 1; j < n; j++) {
if (t[j].population > t[max].population) {
max = j;
}
}
City temp = t[i];
t[i] = t[max];
t[max] = temp;
}
}
int main(void) {
City kaunas = {"Kaunas", 300000, 157.0};
City vilnius = {.name = "Vilnius", .population = 600000, .area = 401.0};
print_city(&kaunas);
print_city(&vilnius);
printf("sizeof(City): %zu\n", sizeof(City));
City copy = kaunas;
copy.population = 0;
printf("kaunas: %d, copy: %d\n", kaunas.population, copy.population);
grow_copy(kaunas, 1000);
printf("After grow_copy: %d\n", kaunas.population);
grow(&kaunas, 1000);
printf("After grow: %d\n", kaunas.population);
City cities[CITY_COUNT] = {
{"Klaipeda", 150000, 98.0}, {"Panevezys", 85000, 50.0}, {"Vilnius", 600000, 401.0},
{"Alytus", 50000, 40.0}, {"Kaunas", 300000, 157.0},
};
sort_by_population(cities, CITY_COUNT);
printf("\nBy population:\n");
for (int i = 0; i < CITY_COUNT; i++) {
printf("%d. ", i + 1);
print_city(&cities[i]);
}
int k = find_city(cities, CITY_COUNT, "Alytus");
if (k != -1) {
printf("Alytus is in place %d, density %.0f people/km2\n", k + 1, density(&cities[k]));
}
if (find_city(cities, CITY_COUNT, "Utena") == -1) {
printf("Utena is not on the list.\n");
}
return 0;
}