Realloc Memory in C

Level 5228 keystrokes

Allocates room for 3 ints, then uses realloc to grow the block to 5 ints; the first 3 values are kept, so after filling the new slots it prints 1 2 3 4 5 and frees the memory.

C code

// First allocates room for only 3 ints
1int *arr = (int *)malloc(3 * sizeof(int));
// Stores 1, 2 and 3 in the three slots
2arr[0] = 1; arr[1] = 2; arr[2] = 3;
3
// Grows the block to 5 ints; realloc may move it but keeps the first 3 values
// Real code should use a temporary pointer: if realloc returns NULL, the old block would leak
4arr = (int *)realloc(arr, 5 * sizeof(int));
// Fills the two new slots with 4 and 5
5arr[3] = 4; arr[4] = 5;
6
// Prints all 5 elements: 1 2 3 4 5
7for (int i = 0; i < 5; i++) {
8 printf("%d ", arr[i]);
9}
// Ends the output line
10printf("\n");
// Frees the resized block once it is no longer needed
11free(arr);

Output

1 2 3 4 5
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ;× 12
  • (× 10
  • )× 10
  • =× 8
  • [× 6
  • ]× 6
  • *× 5
  • "× 4
  • ,× 2
  • +× 2

More C examples at level 5

← C typing practice