← The C Language Lesson 51 of 77 · 10 XP

Resizing: realloc

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

realloc changes the size of a previously allocated block:

int *tmp = realloc(a, new_size * sizeof *a);
if (tmp == NULL) {
    free(a);          // the old block is intact — don't forget to free it
    return 1;
}
a = tmp;

It may extend the block in place, or allocate a new one, copy the data and free the old one. That's why the old pointer must not be used after realloc.

Never write a = realloc(a, ...): if realloc returns NULL, you lose the only pointer to the old memory. That's a leak.

A dynamic array is the basis of list in Python and vector in C++. When it runs out of room, its capacity is doubled. Then adding an item costs O(1) on average:

if (len == cap) {
    cap = cap ? cap * 2 : 4;
    int *tmp = realloc(a, cap * sizeof *a);
    ...
}
a[len++] = x;

Task. Read numbers until the end of the input (how many there are isn't known in advance) into a dynamic array that doubles its capacity. Print the count of numbers and then the numbers themselves in reverse order.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.