From a47d3fe0cf6556f48a32744825c81a2f315d3ebb Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Sat, 27 Dec 2025 12:34:17 +0100 Subject: [PATCH] Aligned allocation --- align_alloc.c | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 align_alloc.c diff --git a/align_alloc.c b/align_alloc.c new file mode 100644 index 0000000..1b9a50d --- /dev/null +++ b/align_alloc.c @@ -0,0 +1,37 @@ +#include +#include +#include +#include +#include +#include +#include + +#define ALLOC_SZ 128 + +int main(void) { + /* glibc defaults to 16 byte alignment with regular malloc on x86_64, and 8 byte for x86 */ + char *mem = aligned_alloc(32, ALLOC_SZ); + char *mem2 = NULL; + + int memalign_status = posix_memalign((void **)&mem2, ALLOC_SZ, ALLOC_SZ); + assert(memalign_status != ENOMEM); + assert(memalign_status != EINVAL); // Fails on non-power-of-two alignment + + char *mem3 = valloc(getpagesize()); + int pgsize = getpagesize(); + printf("Page size: %d\n", pgsize); + + memset(mem, 'B', ALLOC_SZ); + memset(mem2, 'C', ALLOC_SZ); + memset(mem3, 'A', getpagesize()); + + assert((uintptr_t)mem3 % 4096 == 0); + assert((uintptr_t)mem2 % 128 == 0); + assert((uintptr_t)mem % 32 == 0); + + free(mem); + free(mem2); + free(mem3); + + printf("Passed!\n"); +}