Created
February 4, 2024 06:36
-
-
Save denisdemaisbr/cfb9ec98c4ca88e87b05bb0d475f154e to your computer and use it in GitHub Desktop.
strdup with memory aligned
This file contains hidden or 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
// based on original | |
// https://github.com/clibs/strdup/blob/master/strdup. | |
#define strdup_check 1 | |
#define strdup_verbose 0 | |
#define strdup_align(x) (((x)+15)&~15) // 3 (4 bytes), 7 (8 bytes), 15 (16 bytes) | |
static char* strdup_aligned(const char *str) { | |
int len; | |
char* buf; | |
#if strdup_check | |
if (str == NULL || str[0] == 0x0) { | |
#if strdup_verbose | |
printf("[%s] error: string null\n", __FUNCTION__); | |
#endif | |
return NULL; | |
} | |
#endif | |
len = strlen(str) + 1; | |
buf = malloc(strdup_align(len)); | |
if (!buf) { | |
#if strdup_verbose | |
printf("[%s] error: memory alloc\n", __FUNCTION__); | |
#endif | |
errno = ENOMEM; | |
return NULL; | |
} | |
#if strdup_verbose | |
printf("[%s] len=%d aligned=%d\n", __FUNCTION__, len, strdup_align(len)); | |
#endif | |
memset(buf, 0, len); | |
memcpy(buf, str, len - 1); | |
return buf; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment