Browse Source Download (without any required ccan dependencies)

Module:

alignof

Summary:

ALIGNOF() macro to determine alignment of a type.

Author:

Rusty Russell <rusty@rustcorp.com.au>

Description:

Many platforms have requirements that certain types must be aligned to certain address boundaries, such as ints needing to be on 4-byte boundaries. Attempting to access variables with incorrect alignment may cause performance loss or even program failure (eg. a bus signal).

There are times which it's useful to be able to programatically access these requirements, such as for dynamic allocators.

Example:

#include <stdio.h>
#include <stdlib.h>
#include <ccan/alignof/alignof.h>

// Output contains "ALIGNOF(char) == 1"
// Will also print out whether an onstack char array can hold a long.
int main(int argc, char *argv[])
{
        char arr[sizeof(int)];

        printf("ALIGNOF(char) == %zu\n", ALIGNOF(char));
        if ((unsigned long)arr % ALIGNOF(int)) {
                printf("arr %p CANNOT hold an int\n", arr);
                exit(1);
        } else {
                printf("arr %p CAN hold an int\n", arr);
                exit(0);
        }
}

License:

CC0 (Public domain)