Resizing Memory with realloc in C

Level 4204 keystrokes

Uses realloc to resize dynamically allocated memory while preserving existing data. (Real code should keep the old pointer until realloc is known to have succeeded.)

C code

// Allocate memory for 2 integers
1int *arr = (int *)malloc(2 * sizeof(int));
// Initialize first two elements
2arr[0] = 10; arr[1] = 20;
// Grow to 4 ints; old values are kept, but the block may move
3arr = (int *)realloc(arr, 4 * sizeof(int));
// Fill the two new slots (realloc does not initialize them)
4arr[2] = 30; arr[3] = 40;
// Print all four elements
5for (int i = 0; i < 4; i++) {
6 printf("%d ", arr[i]);
7}
// Free the memory
8free(arr);

Output

10 20 30 40 
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.

  • ;× 10
  • (× 9
  • )× 9
  • =× 7
  • [× 5
  • ]× 5
  • *× 5
  • ,× 2
  • "× 2
  • +× 2

More C examples at level 4

← C typing practice