calloc vs malloc in C

Level 5348 keystrokes

Allocates two arrays of 5 ints, one with malloc, whose contents start undefined, and one with calloc, which sets every byte to zero. The malloc array is filled before use and prints 0 10 20 30 40; the calloc array prints 0 0 0 0 0 without any initialization.

C code

// malloc takes one size in bytes and leaves the contents uninitialized (garbage)
1int *arr1 = (int *)malloc(5 * sizeof(int));
// calloc takes a count and an element size, and sets every byte to zero
2int *arr2 = (int *)calloc(5, sizeof(int));
3
// Prints the heading for the malloc array
4printf("malloc (uninitialized):\n");
5for (int i = 0; i < 5; i++) {
// malloc memory must be written before it is read: stores 0, 10, 20, 30, 40
6 arr1[i] = i * 10;
// Prints each value followed by a space
7 printf("%d ", arr1[i]);
8}
9printf("\n");
10
// Prints the heading for the calloc array
11printf("calloc (zero-initialized):\n");
12for (int i = 0; i < 5; i++) {
// No initialization needed: calloc already zeroed it, so this prints 0 0 0 0 0
13 printf("%d ", arr2[i]);
14}
15printf("\n");
16
// Both kinds of allocation are released with free
17free(arr1);
18free(arr2);

Output

malloc (uninitialized):
0 10 20 30 40 
calloc (zero-initialized):
0 0 0 0 0
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.

  • (× 18
  • )× 18
  • ;× 15
  • "× 12
  • *× 6
  • =× 5
  • \× 4
  • +× 4
  • ,× 3
  • [× 3

More C examples at level 5

← C typing practice