C realloc()
Use a temporary pointer for realloc and initialize the newly added elements explicitly.
How it works
realloc can resize an allocated block, move it, or fail. For a nonzero requested size, failure returns null while leaving the old allocation available. Store the result in a temporary pointer so the owner is not lost on failure. After success the old pointer and interior aliases must no longer be used; retain only the new pointer. Bytes beyond the previous allocation size are not initialized. This example never calls realloc with zero, avoiding a difficult boundary that should be handled as an explicit release operation.
Run it locally
Use a hosted C17 compiler in a separate lab folder. The command assumes a driver named cc; substitute gcc, clang or zig cc as appropriate. C does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed for these C programs.
cc -std=c17 -Wall -Wextra -Wpedantic -Werror reallocation.c -o lessonOn Windows, use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Math-library linking differs by toolchain; GCC on many Unix systems needs -lm after the source.
Download the complete C source. File-writing labs must run in an empty private directory, away from existing reports.
Example
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main(void) {
size_t old_count = 2;
size_t new_count = 4;
int *values = malloc(old_count * sizeof *values);
if (values == NULL) { return 1; }
values[0] = 10; values[1] = 12;
if (new_count > SIZE_MAX / sizeof *values) { free(values); return 1; }
int *grown = realloc(values, new_count * sizeof *values);
if (grown == NULL) { free(values); return 1; }
values = grown;
for (size_t i = old_count; i < new_count; ++i) { values[i] = 14; }
printf("Readings: %d %d %d %d\n", values[0], values[1], values[2], values[3]);
free(values);
return 0;
}
Expected result
Readings: 10 12 14 14
The previous two readings survive a successful resize. Only the new elements are initialized in the second loop. On failure, the old block is still freed before returning an error. A dynamic collection should retain both its used length and capacity and update them only after successful growth. Reallocating on every insertion can cause unnecessary copying.
For language and library rules, consult the WG14 C working group and its public C11 committee draft, which describes the core facilities used here; C17 incorporates corrections. Check your compiler and runtime documentation for implementation details.