BETA Try the new lesson view
Drills

Drills: check yourself

Answer first yourself, only then open the answer.

1. What's wrong?

int *p = malloc(10);
for (int i = 0; i < 10; i++) {
    p[i] = i;
}
Answer

malloc(10) is 10 bytes, but 10 int are 40. Already p[2] (bytes 8–11) sticks out of the block (0–9): ASan – heap-buffer-overflow. Also, NULL isn't checked. Correct: malloc(10 * sizeof *p) and if (p == NULL).

2. Will ASan catch it or not?

In step 4's program squares.count = 31, squares.capacity = 32.

  1. printf("%d\n", squares.data[31]);
  2. printf("%d\n", squares.data[32]);
Answer

1 – no: the 32nd place belongs to the block, nothing was written into it, so garbage is printed. 2 – yes: past the end of the block, heap-buffer-overflow. ASan guards the block's bounds, not your count.

3. How many reallocs?

An empty IntArray (capacity 0), array_add is called 100 times. How many times is realloc called, and what is the final capacity?

Answer

6 times: 4, 8, 16, 32, 64, 128. The capacity is 128.

4. Where's the leak?

int average_from_file(const char *path, double *avg) {
    double *t = malloc(100 * sizeof *t);
    if (t == NULL) {
        return 0;
    }
    int count = read_numbers(path, t, 100);
    if (count == 0) {
        return 0;
    }
    *avg = sum(t, count) / count;
    free(t);
    return 1;
}
Answer

When count == 0, the function returns without free(t): LeakSanitizer – detected memory leaks. Before that return you need free(t);.

5. How many bytes?

How many bytes does copy_string("Kaunas") allocate?

Answer

7: strlen is 6, plus 1 for the '\0'.