Aligned allocation

This commit is contained in:
Imbus 2025-12-27 12:34:17 +01:00
parent eedaf13eff
commit a47d3fe0cf

37
align_alloc.c Normal file
View file

@ -0,0 +1,37 @@
#include <assert.h>
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#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");
}