Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

aligned_alloc — allocate memory with specified alignment

aligned_alloc allocates uninitialized memory with a requested alignment. Check the result for NULL and release the memory with free.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <stdlib.h>
void *aligned_alloc(size_t alignment, size_t size);

aligned_alloc from <stdlib.h> allocates size bytes with alignment alignment. The contents are indeterminate: write values before reading them.

Unsupported or invalid alignment returns a null pointer. Allocation can also fail because memory is unavailable. Do not assume every power of two is supported.

N3096, §7.24.3.1, does not require size to be a multiple of alignment. Do not automatically transfer older-version restrictions to this C23 text.

The example uses alignof(int) and releases memory with free. Do not use the pointer after release. A C23 compiler flag does not attest runtime-library conformance.

Examples

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int *p = aligned_alloc(alignof(int), 4 * sizeof *p);
    if (p == NULL) {
        puts("allocation failed");
        return EXIT_FAILURE;
    }

    for (int i = 0; i < 4; ++i) {
        p[i] = i + 1;
    }
    printf("%d\n", p[0] + p[1] + p[2] + p[3]);
    free(p);
    return EXIT_SUCCESS;
}

Result

10

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources