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 zero2int *arr2 = (int *)calloc(5, sizeof(int));3 // Prints the heading for the malloc array4printf("malloc (uninitialized):\n");5for (int i = 0; i < 5; i++) { // malloc memory must be written before it is read: stores 0, 10, 20, 30, 406 arr1[i] = i * 10; // Prints each value followed by a space7 printf("%d ", arr1[i]);8}9printf("\n");10 // Prints the heading for the calloc array11printf("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 013 printf("%d ", arr2[i]);14}15printf("\n");16 // Both kinds of allocation are released with free17free(arr1);18free(arr2);Output
malloc (uninitialized): 0 10 20 30 40 calloc (zero-initialized): 0 0 0 0 0
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