From 54d9167cead9c8513625bb4c5e69edf05bab671a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dag-Erling=20Sm=C3=B8rgrav?= Date: Sun, 3 Mar 2013 23:23:10 +0000 Subject: [PATCH] If ch == '\0', do not grow the string or advance the length counter, but do allocate a string if there is none to begin with. This makes it possible to use openpam_straddch(3) to preallocate the string (if necessary) instead of manually calling malloc(3) or calloc(3) and initializing size and len. git-svn-id: svn+ssh://svn.openpam.org/svn/openpam/trunk@634 185d5e19-27fe-0310-9dcf-9bff6b9f3609 --- lib/openpam_straddch.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/lib/openpam_straddch.c b/lib/openpam_straddch.c index 8f168fc..7150725 100644 --- a/lib/openpam_straddch.c +++ b/lib/openpam_straddch.c @@ -65,7 +65,7 @@ openpam_straddch(char **str, size_t *size, size_t *len, int ch) *str = tmpstr; *size = tmpsize; *len = 0; - } else if (*len + 1 >= *size) { + } else if (ch != 0 && *len + 1 >= *size) { /* additional space required */ tmpsize = *size * 2; if ((tmpstr = realloc(*str, tmpsize)) == NULL) { @@ -76,8 +76,10 @@ openpam_straddch(char **str, size_t *size, size_t *len, int ch) *size = tmpsize; *str = tmpstr; } - (*str)[*len] = ch; - ++*len; + if (ch != 0) { + (*str)[*len] = ch; + ++*len; + } (*str)[*len] = '\0'; return (0); } @@ -94,6 +96,11 @@ openpam_straddch(char **str, size_t *size, size_t *len, int ch) * The =size and =len argument point to variables used to hold the size * of the buffer and the length of the string it contains, respectively. * + * The final argument, =ch, is the character that should be appended to + * the string. If =ch is 0, nothing is appended, but a new buffer is + * still allocated if =str is NULL. This can be used to "bootstrap" the + * string. + * * If a new buffer is allocated or an existing buffer is reallocated to * make room for the additional character, =str and =size are updated * accordingly. @@ -102,7 +109,7 @@ openpam_straddch(char **str, size_t *size, size_t *len, int ch) * NUL-terminated. * * If the =openpam_straddch function is successful, it increments the - * integer variable pointed to by =len and returns 0. + * integer variable pointed to by =len (unless =ch was 0) and returns 0. * Otherwise, it leaves the variables pointed to by =str, =size and =len * unmodified, sets :errno to =ENOMEM and returns -1. *