← The C Language
Lesson 54 of 77 · 10 XP
Typical memory errors
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Memory errors are treacherous: the program often works — until one day it crashes or starts producing garbage.
| error | example |
|---|---|
| going out of bounds | for (i = 0; i <= n; i++) a[i] = 0; — <= instead of < |
no room for the '\0' |
malloc(strlen(s)) instead of strlen(s) + 1 |
| a leak | malloc without free, or p = malloc(...) over an old pointer |
| use-after-free | free(p); printf("%d", *p); |
| double free | free(p); free(p); |
| uninitialised memory | int *a = malloc(...); sum += a[0]; |
| returning the address of a local variable | return &local; |
sizeof of a pointer instead of an array |
malloc(sizeof(p)) instead of sizeof(*p) * n |
How to catch them:
-Wall -Wextra— the compiler warns you about many errors;-fsanitize=address(AddressSanitizer) — the program itself reports going out of bounds and use-after-free at the moment of the error;valgrind ./main— finds leaks.
Task. In the starter code, the function average contains two errors that make the result wrong. The first is a classic out-of-bounds access. In a real program it would read garbage, but here a "foreign" number has been put right after the array on purpose, so that the error becomes visible. The second error is losing the fractional part. Find and fix both. Don't change the main function.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.