diff options
Diffstat (limited to 'util.c')
-rw-r--r-- | util.c | 19 |
1 files changed, 14 insertions, 5 deletions
@@ -65,15 +65,24 @@ static bool streq(char const *a, char const *b) { return strcmp(a, b) == 0; } -// duplicates a null-terminated string. the returned string should be passed to free() -static char *str_dup(char const *src) { +// duplicates at most n characters from src +static char *strn_dup(char const *src, size_t n) { size_t len = strlen(src); - char *ret = malloc(len + 1); - if (ret) - memcpy(ret, src, len + 1); + if (n > len) + n = len; + char *ret = malloc(n + 1); + if (ret) { + memcpy(ret, src, n); + ret[n] = 0; + } return ret; } +// duplicates a null-terminated string. the returned string should be passed to free() +static char *str_dup(char const *src) { + return strn_dup(src, SIZE_MAX); +} + // like snprintf, but not screwed up on windows #define str_printf(str, size, ...) (str)[(size) - 1] = '\0', snprintf((str), (size) - 1, __VA_ARGS__) // like snprintf, but the size is taken to be the length of the array str. |