From: Kefu Chai Date: Wed, 8 Jul 2020 15:33:36 +0000 (+0800) Subject: common/addr_parsing: refactor safe_cat() X-Git-Tag: v16.1.0~1761^2 X-Git-Url: http://git-server-git.apps.pok.os.sepia.ceph.com/?a=commitdiff_plain;h=refs%2Fpull%2F35971%2Fhead;p=ceph.git common/addr_parsing: refactor safe_cat() * add a ROUND_UP_128() macro for calculating the round of to a multiple of 128. * instead of using a loop, use ROUND_UP_128() for the new size of *pstr * rename str2 to src for better readability * use memcpy() instead of strncpy(), as the size of src string is already known this change also silences the warning of ceph/src/common/addr_parsing.c: In function ‘safe_cat’: ceph/src/common/addr_parsing.c:45:3: warning: ‘strncpy’ output truncated before terminating nul copying as many bytes from a string as its length [-Wstringop-truncation] strncpy((*pstr)+pos, str2, len2); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ceph/src/common/addr_parsing.c:28:14: note: length computed here int len2 = strlen(str2); ^~~~~~~~~~~~ Signed-off-by: Kefu Chai --- diff --git a/src/common/addr_parsing.c b/src/common/addr_parsing.c index 4159dff67ceb..0e183c667c2c 100644 --- a/src/common/addr_parsing.c +++ b/src/common/addr_parsing.c @@ -22,29 +22,23 @@ #include #define BUF_SIZE 128 +#define ROUND_UP_128(x) (-(-(x) & -128)) -int safe_cat(char **pstr, int *plen, int pos, const char *str2) +int safe_cat(char **pstr, int *plen, int pos, const char *src) { - int len2 = strlen(str2); - - //printf("safe_cat '%s' max %d pos %d '%s' len %d\n", *pstr, *plen, pos, str2, len2); - while (*plen < pos + len2 + 1) { - *plen += BUF_SIZE; - - void *_realloc = realloc(*pstr, (size_t)*plen); - - if (!_realloc) { + size_t len2 = strlen(src); + size_t new_size = pos + len2 + 1; + if (*plen < new_size) { + size_t round_up = ROUND_UP_128(new_size); + void* p = realloc(*pstr, round_up); + if (!p) { printf("Out of memory\n"); exit(1); } else { - *pstr = _realloc; + *pstr = p; } - //printf("safe_cat '%s' max %d pos %d '%s' len %d\n", *pstr, *plen, pos, str2, len2); } - - strncpy((*pstr)+pos, str2, len2); - (*pstr)[pos+len2] = '\0'; - + memcpy(*pstr + pos, src, len2 + 1); return pos + len2; }