Request and Release an Array
Make room for a variable-sized count
The desk needs three counts in this example. We keep that count in a variable so the allocation expression can use it. malloc requests enough bytes for them and returns a pointer, or NULL on failure. The expression sizeof *counts measures one element without repeating its type. Because the allocated elements start without usable values, check the pointer first and initialize every element before reading it. Release the allocation with free after the last use.
Each row shows the same pointer and three-element allocation at a later moment; question marks mean uninitialized elements, not zeroes.
Read int *counts = malloc(n * sizeof *counts); in pieces:
countsis a pointer toint, not an array that remembers its length.nis the number of elements.size_tis the unsigned integer type used for sizes and counts; keepnso loops know where to stop. Changingnafter allocation would not resize the storage.sizeof *countsgives the size of oneintin bytes. Heresizeofuses the type without reading through the pointer.sizeof countswould measure the pointer itself, not the requested array.- Multiplying the element count by the element size gives the byte count that
mallocexpects. Do not assume every machine uses the same sizes.
fprintf(stderr, ...) sends the allocation-failure message to the diagnostic stream rather than ordinary output. The following section explains these streams in more detail.
In C, malloc's result converts to the destination pointer type without a cast. Include <stdlib.h> so the compiler knows the function's declaration. Our small, positive count is fixed; a general program must also reject counts whose multiplication would overflow or request an impractical amount of memory. Zero-size allocations are not needed here.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t n = 3;
int *counts = malloc(n * sizeof *counts);
if (counts == NULL) {
fprintf(stderr, "Allocation failed\n");
return 1;
}
for (size_t i = 0; i < n; i++) {
counts[i] = (int) (i + 1);
}
printf("Total: %d\n", counts[0] + counts[1] + counts[2]);
free(counts);
counts = NULL;
return 0;
}
The loop writes indexes 0, 1, and 2 with values 1, 2, and 3. Only then does printf read them and print Total: 6. Index 3 is outside this three-element array. No array element is read before it has a value. counts = NULL records that this variable no longer refers to usable storage. Dereferencing it would still be invalid, and the assignment cannot repair other copies of the freed address. For the exercise, repeat that order with different counts: allocate, check, fill, read, free.