Skip to content

Instantly share code, notes, and snippets.

@pstrinkle
Last active May 20, 2016 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pstrinkle/4761a1349fda708c86019e8ea0543b1b to your computer and use it in GitHub Desktop.
Save pstrinkle/4761a1349fda708c86019e8ea0543b1b to your computer and use it in GitHub Desktop.
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
Copy link
Author

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