prefer memcpy to strcpy
authorJeff King <peff@peff.net>
Thu, 24 Sep 2015 21:08:19 +0000 (17:08 -0400)
committerJunio C Hamano <gitster@pobox.com>
Mon, 5 Oct 2015 18:08:05 +0000 (11:08 -0700)
When we already know the length of a string (e.g., because
we just malloc'd to fit it), it's nicer to use memcpy than
strcpy, as it makes it more obvious that we are not going to
overflow the buffer (because the size we pass matches the
size in the allocation).

This also eliminates calls to strcpy, which make auditing
the code base harder.

Signed-off-by: Jeff King <peff@peff.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
compat/nedmalloc/nedmalloc.c
fast-import.c
revision.c
index 609ebba1258eac47983f2b9da5d582a5d5af5482..a0a16eb1bbfb22c13f29c15d2fd68ccc9c7e01ad 100644 (file)
@@ -957,8 +957,9 @@ char *strdup(const char *s1)
 {
        char *s2 = 0;
        if (s1) {
-               s2 = malloc(strlen(s1) + 1);
-               strcpy(s2, s1);
+               size_t len = strlen(s1) + 1;
+               s2 = malloc(len);
+               memcpy(s2, s1, len);
        }
        return s2;
 }
index 895c6b4a7ee6925fd2a852a612616cc8f5ece9c9..cf6d8bc0ce430b5c6a05fd26e2abd9d473e8c832 100644 (file)
@@ -644,8 +644,9 @@ static void *pool_calloc(size_t count, size_t size)
 
 static char *pool_strdup(const char *s)
 {
-       char *r = pool_alloc(strlen(s) + 1);
-       strcpy(r, s);
+       size_t len = strlen(s) + 1;
+       char *r = pool_alloc(len);
+       memcpy(r, s, len);
        return r;
 }
 
index af2a18ed7485ea83170409ce55f81473ee606221..22364636d1456795dd858b8039da3b90d32c6633 100644 (file)
@@ -38,7 +38,7 @@ char *path_name(const struct name_path *path, const char *name)
        }
        n = xmalloc(len);
        m = n + len - (nlen + 1);
-       strcpy(m, name);
+       memcpy(m, name, nlen + 1);
        for (p = path; p; p = p->up) {
                if (p->elem_len) {
                        m -= p->elem_len + 1;