]> git.apps.os.sepia.ceph.com Git - ceph.git/commitdiff
common/addr_parsing: refactor safe_cat() 35971/head
authorKefu Chai <kchai@redhat.com>
Wed, 8 Jul 2020 15:33:36 +0000 (23:33 +0800)
committerKefu Chai <kchai@redhat.com>
Wed, 8 Jul 2020 16:35:30 +0000 (00:35 +0800)
* 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 <kchai@redhat.com>
src/common/addr_parsing.c

index 4159dff67cebb8528d335937e1b57db63026eee4..0e183c667c2cdd09e150306a1718ed71fe9a7743 100644 (file)
 #include <netdb.h>
 
 #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;
 }