Last active
May 20, 2016 15:54
-
-
Save pstrinkle/4761a1349fda708c86019e8ea0543b1b to your computer and use it in GitHub Desktop.
memory-alignment for allocation in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just trying out gist by publishing code that I find I often need.