Skip to content

Allocate and Initialize

The Course
•
35 min study

Yesterday's array had a size written into the source: int data[2]. Real input does not announce its size in advance. The analyzer might read three lines or a thousand, and an array sized for the worst case wastes memory in the common case and still has a limit. C's answer is the heap: memory you request while the program runs, in exactly the amount you need, and keep for as long as you need it.

malloc (from <stdlib.h>) requests a number of bytes and returns a pointer to the first one, or NULL when it cannot provide them. That one sentence holds three obligations: compute the byte count correctly, check for NULL, and give the bytes values before reading them. A fourth, releasing the memory with free, is the subject of the next lessons.

Predict and run

Read the program before pressing Run. Write down its output and explain which statement produces it.

Predict before running C
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *values = malloc(3 * sizeof *values);
    if (values == NULL) { return 1; }
    for (size_t i = 0; i < 3; ++i) { values[i] = (int)i + 1; }
    printf("%d\n", values[0] + values[1] + values[2]);
    free(values);
    return 0;
}
Check your prediction
Text
6

The loop stores 1, 2 and 3, so the sum is 6. The pointer values is used like an array name: values[i] means "the element i places after the first".

Size the request from the pointer

malloc returns void *, which converts to any object pointer type in C without a cast. Write the size as count * sizeof *values: "count elements of whatever values points to". The expression after sizeof is not evaluated, so *values is not a dereference and is safe before the pointer has a value.

The habit matters when types change. Compare:

C
double *averages = malloc(3 * sizeof(int));     /* too small: wrong type named */
double *averages = malloc(3 * sizeof *averages); /* always matches */

On a typical platform the first line reserves 12 bytes for 24 bytes of double values, and writing the third element runs off the end of the block. Nothing in the language catches the mismatch. The second form follows the pointer's type automatically.

Check for NULL before the first use

When malloc fails, it returns NULL and there is no object to use. Writing through that pointer is undefined behavior. Recall from Day 1 that the compiler may assume undefined behavior never happens, so a NULL check placed after the first write can be optimized away. Check immediately after the call, and give the caller a status or an exit code:

C
int *values = malloc(count * sizeof *values);
if (values == NULL) {
    return STATUS_NOMEM;
}

On a desktop machine a small request almost never fails, which is why untested failure paths are common. Day 6 shows how to make allocation fail on purpose in a test.

Fresh bytes have no values yet

The memory malloc returns is uninitialized. Reading an element before writing it gives an indeterminate value: it may look like 0 in one run and like garbage in the next, and tools such as Valgrind and MemorySanitizer report it as an error. Never print such values as "expected output". Write every element you will read:

Initialize, then read C
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    size_t count = 4;
    int *minutes = malloc(count * sizeof *minutes);
    if (minutes == NULL) { return 1; }
    for (size_t i = 0; i < count; ++i) {
        minutes[i] = 15 * (int)(i + 1);
    }
    long total = 0;
    for (size_t i = 0; i < count; ++i) { total += minutes[i]; }
    printf("%zu sessions, %ld minutes\n", count, total);
    free(minutes);
    return 0;
}
Text
4 sessions, 150 minutes

Heap storage outlives the function that requested it

A local array dies when its function returns. Returning its address is a classic bug: the caller receives a pointer to storage that no longer exists, and reading it is undefined behavior.

C
int *broken_range(void) {
    int numbers[3] = {1, 2, 3};
    return numbers;   /* numbers ends here; the pointer dangles */
}

Compilers warn about this one (address of stack memory associated with local variable returned). Heap storage is different: it stays valid until someone passes the pointer to free. That is what makes it useful, and also what makes it your responsibility. free must be called exactly once for each successful allocation. Calling free(NULL) is allowed and does nothing, which later lessons use to simplify cleanup.

Practice

Exercise

Your turn

Write int *make_squares(size_t n) that returns a heap array holding 1, 4, 9 ... up to n * n, or NULL when n is 0 or allocation fails. In main, build 5 squares, print them on one line, free them, and then show that make_squares(0) returns NULL. The output must be squares: 1 4 9 16 25 followed by n = 0: NULL.

Your workspace C
#include <stdio.h>
#include <stdlib.h>

/* Write make_squares here. */

int main(void) {
    // Build, print and free five squares, then try n = 0.
    return 0;
}
Hint 1: the idea

The function allocates and initializes; the caller uses and frees. The caller must check for NULL before printing, because a failed call gives no array.

Hint 2: a first step

Write main's side first, against a make_squares that only returns NULL: the NULL check before printing, and the free. Run it and confirm the n = 0: NULL line appears and nothing crashes. Then write the allocation, decide what it does when malloc fails, and only then fill the array.

Show one solution
Run the solution C
#include <stdio.h>
#include <stdlib.h>

int *make_squares(size_t n) {
    if (n == 0) { return NULL; }
    int *squares = malloc(n * sizeof *squares);
    if (squares == NULL) { return NULL; }
    for (size_t i = 0; i < n; ++i) {
        squares[i] = (int)((i + 1) * (i + 1));
    }
    return squares;
}

int main(void) {
    int *squares = make_squares(5);
    if (squares == NULL) { return 1; }
    printf("squares:");
    for (size_t i = 0; i < 5; ++i) { printf(" %d", squares[i]); }
    printf("\n");
    free(squares);
    printf("n = 0: %s\n", make_squares(0) == NULL ? "NULL" : "allocated");
    return 0;
}
Text
squares: 1 4 9 16 25
n = 0: NULL

Every element is written before main reads it, and the single free matches the single successful malloc. The stated output assumes allocation succeeds; if it failed, main would return 1 without printing. One gap remains: for a very large n, n * sizeof *squares could wrap to a small number. The next lesson closes it with a checked byte count.

Was this article helpful?

Your response is saved on this device.