Skip to content

Instantly share code, notes, and snippets.

@aneury1
Last active June 21, 2020 16:58
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 aneury1/057f5e9e587a28ff43ebc8e1df53eaf6 to your computer and use it in GitHub Desktop.
Save aneury1/057f5e9e587a28ff43ebc8e1df53eaf6 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
void* aligned_malloc(size_t required_bytes, size_t alignment)
{
void* p1; // original block
void** p2; // aligned block
int offset = alignment - 1 + sizeof(void*);
if ((p1 = (void*)malloc(required_bytes + offset)) == NULL)
{
return NULL;
}
p2 = (void**)(((size_t)(p1) + offset) & ~(alignment - 1));
p2[-1] = p1;
return p2;
}
void aligned_free(void *p)
{
free(((void**)p)[-1]);
}
void main (int argc, char *argv[])
{
char **endptr;
int *p = aligned_malloc (100, strtol(argv[1], endptr, 10));
printf ("%s: %p\n", argv[1], p);
aligned_free (p);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment