Skip to content

Instantly share code, notes, and snippets.

@pstrinkle pstrinkle/mem.c
Last active May 20, 2016

Embed
What would you like to do?
memory-alignment for allocation in C
/*
* In this example, we don't used fixed-length types, which bugs me, but the idea is that it has to work on memory-length numbers.
*
* So it takes long, which is memory address length. So, you can change it to uint64_t or uint32_t, or just ints or size_t if you want
* and it should mostly work. However, for this exmaple to be complete, I needed the rounding to support memory addresses as input.
*/
/* 4KiB for this example. */
#define ALIGNMENT_SIZE 0x1000
#define NULL ((void*)0)
/*
* Round a value down to the alignment.
*/
static long
roundDown(long size) {
return (size & (~(ALIGNMENT_SIZE - 1)));
}
/*
* Round up a number to be in ALIGNMENT_SIZE blocks.
*/
static long
roundUp(long size) {
if (0 == size) {
return (ALIGNMENT_SIZE);
}
return ((size + ALIGNMENT_SIZE - 1) & (~(ALIGNMENT_SIZE - 1)));
}
/*
* If you can't guarantee 4KiB alignment, but need it for whatever interface.
*
* This will return a guaranteed 4KiB aligned address.
*/
static void *
alignMalloc(long size) {
void *m = malloc(roundUp(size));
if (m) {
return (void *)roundDown(m);
} else {
return NULL;
}
}
@pstrinkle

This comment has been minimized.

Copy link
Owner Author

pstrinkle commented May 20, 2016

Just trying out gist by publishing code that I find I often need.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.