C programming · CM10 · 90 minutes
ISTIC · University of Rennes
2026–2027
Call visit() twice. What survives between the calls?
A typical layout, not a C language guarantee. Not to scale.
Static storage
Globals and static objects exist for the whole program. Storage is reserved before execution.
Automatic storage
An ordinary local exists during its block execution. Each recursive call gets its own locals.
The implementation manages their storage. Deep recursion can exhaust the stack.
size_t count;
if (scanf("%zu", &count) != 1) return EXIT_FAILURE;
if (count == 0 || count > 1000) return EXIT_FAILURE;
int *p = malloc(count * sizeof *p);
if (p == NULL) return EXIT_FAILURE;The size is chosen during execution. The allocation can outlive the function that creates it.
Download C example ↓One contiguous allocation
Valid indices are 0 ≤ i < count. Write each value before reading it.
freeEnd the allocation's lifetime
Pass the start address of a live allocation from malloc, calloc or realloc. free returns no value.
free(NULL) has no effect. Free each allocation once.
Invalid or repeated free is undefined behaviour.
<stdlib.h>| Function | Purpose |
|---|---|
malloc(bytes) |
Allocate uninitialised storage |
calloc(count, size) |
Allocate storage with all bits zero |
realloc(p, bytes) |
Resize an allocation; it may move |
free(p) |
Release an allocation |
Read the error summary, then the heap summary. A program can print the expected result and still misuse memory.
Download C example ↓int *a = malloc(4 * sizeof *a);
if (!a) return EXIT_FAILURE;
for (size_t i = 0; i <= 4; ++i)
a[i] = (int)(10 * (i + 1));Which iteration writes outside the allocation?
C: explicit responsibility
For every successful allocation, decide who will release it and when. Repeated leaks consume more memory.
Java: garbage collection
The runtime can reclaim unreachable objects automatically.
Answer questions 1–5, then discuss your reasoning.
Predict the values of p and s, and the fate of the allocation.
The literals are separate from the lost heap block. Neither pointer can now be passed to free.
int *m[4]; // Automatic table of four pointers.
for (size_t i = 0; i < 4; ++i)
m[i] = malloc(3 * sizeof *m[i]);Check each row. Use m[i][j]; free each row, not m.
Answer questions 6–8, then discuss your reasoning.
Three tools
enum names integer constants. struct groups members. typedef introduces a name for a type.
Use them to describe more complex data, including list nodes.
Padding
The implementation may insert unused bytes between members and at the end to satisfy alignment requirements.
sizeof(struct T) includes padding.typedef: a name for a typeA_DATE today = { wed, { 3, 9, 2014 } };
today.day = wed;
today.date.year = 2014;
A_DATE *p = &today;
p->day = today.day;
p->date.year = 2026;p->date.year reaches the nested member of the same object.