Dynamic Memory Allocation in C

Level 5246 keystrokes

Allocates an array of 5 ints on the heap with malloc, stops with an error if the allocation fails, fills it with 10, 20, 30, 40, 50 and prints them. Finally it releases the memory with free.

C code

// Requests room for 5 ints on the heap; malloc returns void*, cast here to int*
1int *arr = (int *)malloc(5 * sizeof(int));
// malloc returns NULL when no memory is available, so this must be checked first
2if (arr == NULL) {
// Reports the failure
3 printf("Memory allocation failed\n");
// Ends with a non-zero value, which signals an error
4 return 1;
5}
// Fills the 5 elements one by one
6for (int i = 0; i < 5; i++) {
// Stores (i + 1) * 10, giving 10, 20, 30, 40, 50
7 arr[i] = (i + 1) * 10;
8}
// Walks through the array again to print it
9for (int i = 0; i < 5; i++) {
// Prints each value followed by a space: 10 20 30 40 50
10 printf("%d ", arr[i]);
11}
// Ends the output line
12printf("\n");
// Returns the heap memory to the system; every malloc needs a matching free
13free(arr);

Output

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

  • ;× 11
  • (× 11
  • )× 11
  • "× 6
  • =× 6
  • +× 5
  • *× 4
  • {× 3
  • }× 3
  • [× 2

More C examples at level 5

← C typing practice