Allocating memory

suggest change

The dynamic-memory functions are declared in <stdlib.h>. To allocate space for ten int objects:

int *values = malloc(10 * sizeof *values);
if (values == NULL) {
    perror("malloc");
    return EXIT_FAILURE;
}

Using sizeof *values derives the element size from the pointer's type, so the allocation stays correct if that type changes. Check the result before dereferencing it. For a runtime element count, first ensure that count <= SIZE_MAX / sizeof *values so the multiplication cannot wrap.

Storage returned by malloc has indeterminate contents. Initialize an object before reading it. When an all-bits-zero initial value is appropriate, calloc is convenient and also checks whether the size multiplication overflows:

int *values = calloc(count, sizeof *values);
if (values == NULL) {
    perror("calloc");
    return EXIT_FAILURE;
}

All-bits-zero is not guaranteed to represent a floating-point zero or a null pointer on every C implementation.

Release dynamic storage with free when it is no longer needed:

free(values);
values = NULL;

Assigning NULL is useful when the pointer remains in scope, but it does not affect other pointers to the same allocation.

Over-aligned storage

C11 introduced aligned_alloc for alignments greater than the fundamental alignment guaranteed by malloc and calloc:

void *block = aligned_alloc(256, 1024);
if (block == NULL) {
    perror("aligned_alloc");
    return EXIT_FAILURE;
}

free(block);

The requested alignment must be valid and supported by the implementation. C11 as originally published also required the size to be an integral multiple of the alignment; rounding up to such a multiple remains useful when targeting older implementations.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents