malloc Allocation in C

Level 4195 keystrokes

Demonstrates dynamic memory allocation with malloc and proper cleanup with free.

C code

// Number of elements to allocate
1int n = 5;
// Allocate n * sizeof(int) bytes; the contents start uninitialized
2int *arr = (int *)malloc(n * sizeof(int));
// Always check if allocation succeeded
3if (arr != NULL) {
// Fill the array with 10, 20, 30, 40, 50
4 for (int i = 0; i < n; i++) {
5 arr[i] = (i + 1) * 10;
6 }
// Print array elements
7 for (int i = 0; i < n; i++) {
8 printf("%d ", arr[i]);
9 }
// Free allocated memory to avoid leaks
10 free(arr);
11}

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.

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

More C examples at level 4

← C typing practice