Last active
June 21, 2020 16:58
-
-
Save aneury1/057f5e9e587a28ff43ebc8e1df53eaf6 to your computer and use it in GitHub Desktop.
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
#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