diff --git a/ChangeLog b/ChangeLog index a95aec2e2765e250b9cf49c7aa497c60e4be6318..69edcebaa17741360789c13cc79fb64581ee7410 100644 --- a/ChangeLog +++ b/ChangeLog @@ -238,6 +238,11 @@ CVS code - regexp_bol_or_eol() - Don't assume any longer that string will be found if REG_NOTBOL and REG_NOTEOL are not set. (DLR) + mallocstrncpy() + - New function, used as a malloc()ing equivalent of strncpy(). + (DLR) + mallocstrcpy() + - Refactor to be a wrapper for mallocstrncpy(). (DLR) - winio.c: unget_kbinput() - New function used as a wrapper for ungetch(). (DLR) diff --git a/src/proto.h b/src/proto.h index bf8a7e190a4002d7843d7390ea838949c169f0a1..c0a2e16ab52dcf1ab4a9f1cbf44d4827e4655c92 100644 --- a/src/proto.h +++ b/src/proto.h @@ -490,6 +490,7 @@ const char *strstrwrapper(const char *haystack, const char *needle, void nperror(const char *s); void *nmalloc(size_t howmuch); void *nrealloc(void *ptr, size_t howmuch); +char *mallocstrncpy(char *dest, const char *src, size_t n); char *mallocstrcpy(char *dest, const char *src); char *mallocstrassn(char *dest, char *src); void new_magicline(void); diff --git a/src/search.c b/src/search.c index 7cea9f2b5fc0d23a04a88e3e53dd50223b6adbc0..185e9aa0efd4b8ab4a3de232bd69596096b1c4c9 100644 --- a/src/search.c +++ b/src/search.c @@ -315,8 +315,7 @@ bool findnextstr(bool can_display_wrap, bool wholeword, bool /* If we're searching for whole words, see if this potential * match is a whole word. */ if (wholeword) { - char *word = charalloc(found_len + 1); - strncpy(word, found, found_len); + char *word = mallocstrncpy(word, found, found_len + 1); word[found_len] = '\0'; found_whole = is_whole_word(found - fileptr->data, diff --git a/src/utils.c b/src/utils.c index bee1c6cf691a3eb3a9d21545ec1e07695a8a4a47..b113cb955607257b63e8ed5d7e6b6d7a28d98466 100644 --- a/src/utils.c +++ b/src/utils.c @@ -394,9 +394,10 @@ void *nrealloc(void *ptr, size_t howmuch) return r; } -/* Copy one malloc()ed string to another pointer. Should be used as: - * "dest = mallocstrcpy(dest, src);". */ -char *mallocstrcpy(char *dest, const char *src) +/* Copy the first n characters of one malloc()ed string to another + * pointer. Should be used as: "dest = mallocstrncpy(dest, src, + * n);". */ +char *mallocstrncpy(char *dest, const char *src, size_t n) { if (src == NULL) src = ""; @@ -404,12 +405,19 @@ char *mallocstrcpy(char *dest, const char *src) if (src != dest) free(dest); - dest = charalloc(strlen(src) + 1); - strcpy(dest, src); + dest = charalloc(n); + strncpy(dest, src, n); return dest; } +/* Copy one malloc()ed string to another pointer. Should be used as: + * "dest = mallocstrcpy(dest, src);". */ +char *mallocstrcpy(char *dest, const char *src) +{ + return mallocstrncpy(dest, src, src == NULL ? 1 : strlen(src) + 1); +} + /* Free the malloc()ed string at dest and return the malloc()ed string * at src. Should be used as: "answer = mallocstrassn(answer, * real_dir_from_tilde(answer));". */