Skip to the task
Layout
Back to classic view

You are looking ahead. Your place is still task 1: malloc.

READTask 2 of 20 · step 2: realloc and AddressSanitizerrealloc and ASan
realloc and ASan in practice/07/

realloc through a temporary pointer, count and capacity, doubling the capacity, AddressSanitizer: heap-buffer-overflow, heap-use-after-free, memory leaks.

Details & hint

Sometimes you don't know in advance how many elements there will be: how many lines are in a file, how many students a person will enter. Then the array grows as it goes.

realloc

realloc(p, new_bytes) grows (or shrinks) a block. If there's no room next to it, it allocates a new block, copies the contents, frees the old one and returns a new address. If it got no memory, it returns NULL and the old block is left untouched.

So the result goes into a temporary pointer first:

int *new_data = realloc(m->data, (size_t)new_capacity * sizeof *new_data);
if (new_data == NULL) {
    return 0; /* m->data is still valid */
}
m->data = new_data;

m->data = realloc(m->data, ...) won't do: on NULL the old address is lost and the block can never be freed. realloc(NULL, n) works like malloc(n) – so an empty array can start out as NULL.

How many, how many fit

typedef struct {
    int *data;    /* the elements in dynamic memory, or NULL */
    int count;    /* how many elements are stored */
    int capacity; /* how many fit before it has to grow */
} IntArray;

When count == capacity, the capacity is doubled: 4, 8, 16, 32… If you grew it by one, every addition would call realloc and maybe copy everything again. With doubling, 1000 elements need only 9 realloc calls (4 → 1024), and the empty space is never more than half.

AddressSanitizer

Memory errors in C are often invisible: the program writes past a block or reads memory already freed and still "works" – until it stops working somewhere else. GitHub CI compiles the course tests with AddressSanitizer and UndefinedBehaviorSanitizer (the ci preset). They watch every memory access and stop the program at the first error:

report what happened
heap-buffer-overflow past the end of a malloc block
heap-use-after-free after free
attempting double-free free twice
LeakSanitizer: detected memory leaks the program ended and memory wasn't freed

The report is long, but what matters is the line with ERROR and the first file in the list that is yours. For example, if in step 4's program you wrote printf("%d\n", squares.data[squares.capacity]); after the Last line (line 70), GitHub CI would show this report (a real one; only the path up to the repository is shortened to ...):

=================================================================
==17435==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x7b2ac3fe00c0 at pc 0x5ab858ae71b4 bp 0x7ffcaa7f2b90 sp 0x7ffcaa7f2b80
READ of size 4 at 0x7b2ac3fe00c0 thread T0
    #0 0x5ab858ae71b3 in main .../practice/12/memory.c:71
    #1 0x7e6ac502a8c0  (/usr/lib/x86_64-linux-gnu/libc.so.6+0x2a8c0) (BuildId: 86304dcc94791043688c314c38955023b3ccc64a)
    #2 0x7e6ac502a9d7 in __libc_start_main (/usr/lib/x86_64-linux-gnu/libc.so.6+0x2a9d7) (BuildId: 86304dcc94791043688c314c38955023b3ccc64a)
    #3 0x5ab858ae6364 in _start (.../build/ci/practice/12/p12_memory+0x3364) (BuildId: 69b91ccfb130b840070f528bfbcce9ee7eae67a9)

0x7b2ac3fe00c0 is located 0 bytes after 128-byte region [0x7b2ac3fe0040,0x7b2ac3fe00c0)
allocated by thread T0 here:
    #0 0x7e6ac5d28e9f in realloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:81
    #1 0x5ab858ae6879 in array_add .../practice/12/memory.c:27
    #2 0x5ab858ae6e94 in main .../practice/12/memory.c:63
    #3 0x7e6ac502a8c0  (/usr/lib/x86_64-linux-gnu/libc.so.6+0x2a8c0) (BuildId: 86304dcc94791043688c314c38955023b3ccc64a)
    #4 0x7e6ac502a9d7 in __libc_start_main (/usr/lib/x86_64-linux-gnu/libc.so.6+0x2a9d7) (BuildId: 86304dcc94791043688c314c38955023b3ccc64a)
    #5 0x5ab858ae6364 in _start (.../build/ci/practice/12/p12_memory+0x3364) (BuildId: 69b91ccfb130b840070f528bfbcce9ee7eae67a9)

SUMMARY: AddressSanitizer: heap-buffer-overflow .../practice/12/memory.c:71 in main
Shadow bytes around the buggy address:
  0x7b2ac3fdfe00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x7b2ac3fdfe80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x7b2ac3fdff00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x7b2ac3fdff80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x7b2ac3fe0000: fa fa fa fa fa fa fa fa 00 00 00 00 00 00 00 00
=>0x7b2ac3fe0080: 00 00 00 00 00 00 00 00[fa]fa fa fa fa fa fa fa
  0x7b2ac3fe0100: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x7b2ac3fe0180: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x7b2ac3fe0200: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x7b2ac3fe0280: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x7b2ac3fe0300: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07 
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
==17435==ABORTING

Read it from the top:

  • heap-buffer-overflow, READ of size 4 – 4 bytes (one int) are read past the end of a block;
  • #0 ... in main .../practice/12/memory.c:71 – where: the function main, line 71. #1–#3 are the C library calls that started main; you don't need them;
  • 0 bytes after 128-byte region – right after a 128-byte block (32 int, capacity 32);
  • allocated by thread T0 here – where that block came from: realloc in the function array_add (line 27), called by main (line 63);
  • SUMMARY – the same place in one line. The Shadow bytes table is ASan's internal map; you don't need to read it.

The compiler doesn't warn here: the block's size is only known at run time. The program's output (Capacity: 0 -> 4…) isn't there before the report: it was still in the buffer (topic 11) when ASan stopped the program.

Use after free: the whole report

Before array_free(&squares); a pointer is kept, int *last = &squares.data[squares.count - 1]; (the new line 71), and after it printf("%d\n", *last); prints through it (line 73):

=================================================================
==17451==ERROR: AddressSanitizer: heap-use-after-free on address 0x7a12641e00b8 at pc 0x6383e6fe41cb bp 0x7ffc60432800 sp 0x7ffc604327f0
READ of size 4 at 0x7a12641e00b8 thread T0
    #0 0x6383e6fe41ca in main .../practice/12/memory.c:73
    #1 0x7d526522a8c0  (/usr/lib/x86_64-linux-gnu/libc.so.6+0x2a8c0) (BuildId: 86304dcc94791043688c314c38955023b3ccc64a)
    #2 0x7d526522a9d7 in __libc_start_main (/usr/lib/x86_64-linux-gnu/libc.so.6+0x2a9d7) (BuildId: 86304dcc94791043688c314c38955023b3ccc64a)
    #3 0x6383e6fe3364 in _start (.../build/ci/practice/12/p12_memory+0x3364) (BuildId: a15c0383c190ec421f2fbf2055103b58fe3a77e1)

0x7a12641e00b8 is located 120 bytes inside of 128-byte region [0x7a12641e0040,0x7a12641e00c0)
freed by thread T0 here:
    #0 0x7d5265f28bcf in free ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:51
    #1 0x6383e6fe3cf3 in array_free .../practice/12/memory.c:43
    #2 0x6383e6fe4162 in main .../practice/12/memory.c:72
    #3 0x7d526522a8c0  (/usr/lib/x86_64-linux-gnu/libc.so.6+0x2a8c0) (BuildId: 86304dcc94791043688c314c38955023b3ccc64a)
    #4 0x7d526522a9d7 in __libc_start_main (/usr/lib/x86_64-linux-gnu/libc.so.6+0x2a9d7) (BuildId: 86304dcc94791043688c314c38955023b3ccc64a)
    #5 0x6383e6fe3364 in _start (.../build/ci/practice/12/p12_memory+0x3364) (BuildId: a15c0383c190ec421f2fbf2055103b58fe3a77e1)

previously allocated by thread T0 here:
    #0 0x7d5265f28e9f in realloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:81
    #1 0x6383e6fe3879 in array_add .../practice/12/memory.c:27
    #2 0x6383e6fe3e94 in main .../practice/12/memory.c:63
    #3 0x7d526522a8c0  (/usr/lib/x86_64-linux-gnu/libc.so.6+0x2a8c0) (BuildId: 86304dcc94791043688c314c38955023b3ccc64a)
    #4 0x7d526522a9d7 in __libc_start_main (/usr/lib/x86_64-linux-gnu/libc.so.6+0x2a9d7) (BuildId: 86304dcc94791043688c314c38955023b3ccc64a)
    #5 0x6383e6fe3364 in _start (.../build/ci/practice/12/p12_memory+0x3364) (BuildId: a15c0383c190ec421f2fbf2055103b58fe3a77e1)

SUMMARY: AddressSanitizer: heap-use-after-free .../practice/12/memory.c:73 in main
Shadow bytes around the buggy address:
  0x7a12641dfe00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x7a12641dfe80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x7a12641dff00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x7a12641dff80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x7a12641e0000: fa fa fa fa fa fa fa fa fd fd fd fd fd fd fd fd
=>0x7a12641e0080: fd fd fd fd fd fd fd[fd]fa fa fa fa fa fa fa fa
  0x7a12641e0100: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x7a12641e0180: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x7a12641e0200: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x7a12641e0280: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x7a12641e0300: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07 
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
==17451==ABORTING

Three lists: where it is read (main, 73), where the block was freed (free in the function array_free, line 43, called from 72) and where it came from (array_add, 27). In the table, fd is freed memory.

A leak: the whole report

Without free(name); (line 79):

=================================================================
==17464==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 13 byte(s) in 1 object(s) allocated from:
    #0 0x77db20b29ddf in malloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:67
    #1 0x597ab6d7ed4d in copy_string .../practice/12/memory.c:51
    #2 0x597ab6d7f0d5 in main .../practice/12/memory.c:73
    #3 0x77db1fe2a8c0  (/usr/lib/x86_64-linux-gnu/libc.so.6+0x2a8c0) (BuildId: 86304dcc94791043688c314c38955023b3ccc64a)
    #4 0x77db1fe2a9d7 in __libc_start_main (/usr/lib/x86_64-linux-gnu/libc.so.6+0x2a9d7) (BuildId: 86304dcc94791043688c314c38955023b3ccc64a)
    #5 0x597ab6d7e364 in _start (.../build/ci/practice/12/p12_memory+0x3364) (BuildId: 114239795614abfac4d67f279ecb8bfbf5360eda)

SUMMARY: AddressSanitizer: 13 byte(s) leaked in 1 allocation(s).

Direct leak of 13 byte(s) – the copy of "Ona Petraite" (13 bytes, as the program printed in step 4), allocated in the function copy_string (line 51), called by main (73). LeakSanitizer checks when the program ends, and here too the program's output is missing: it stayed in the buffer.

GitHub CI catches some of these mistakes even earlier. Its GCC is newer than CLion's and refuses code that still uses p after free(p) in the same function, e.g. free(name); twice in a row: pointer ‘name’ used after ‘free’ [-Werror=use-after-free]. When the free and the use are in different functions, the compiler can't see it, and ASan is what's left.

MinGW (CLion on Windows) doesn't have these tools: a program that "works" for you may stop on GitHub. From this topic on, the rule: the tests pass with ASan and UBSan too.

practice 07 daytime.c Code Diff
UNCHANGED This step does not change this file.
#include "daytime.h"
#include <assert.h>
#include <stdio.h>
#include "input.h"
int is_time(int hour, int min) {
return hour >= 0 && hour <= 23 && min >= 0 && min <= 59;
}
int to_minutes(int hour, int min) {
assert(is_time(hour, min));
return hour * 60 + min;
}
int read_time(void) {
int hour = read_int("Hour: ");
int min = read_int("Minutes: ");
while (!is_time(hour, min)) {
printf("There is no such time.\n");
hour = read_int("Hour: ");
min = read_int("Minutes: ");
}
return to_minutes(hour, min);
}
void print_time(int minutes) {
assert(minutes >= 0 && minutes < MINUTES_PER_DAY);
printf("%02d:%02d", minutes / 60, minutes % 60);
}
void print_duration(int minutes) {
assert(minutes >= 0);
printf("%d min (%d h %d min)", minutes, minutes / 60, minutes % 60);
}