Skip to content

Commit 34fa79a

Browse files
peffgitster
authored andcommitted
prefer memcpy to strcpy
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 <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 4c9ac3b commit 34fa79a

File tree

3 files changed

+7
-5
lines changed

3 files changed

+7
-5
lines changed

compat/nedmalloc/nedmalloc.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -957,8 +957,9 @@ char *strdup(const char *s1)
957957
{
958958
char *s2 = 0;
959959
if (s1) {
960-
s2 = malloc(strlen(s1) + 1);
961-
strcpy(s2, s1);
960+
size_t len = strlen(s1) + 1;
961+
s2 = malloc(len);
962+
memcpy(s2, s1, len);
962963
}
963964
return s2;
964965
}

fast-import.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -644,8 +644,9 @@ static void *pool_calloc(size_t count, size_t size)
644644

645645
static char *pool_strdup(const char *s)
646646
{
647-
char *r = pool_alloc(strlen(s) + 1);
648-
strcpy(r, s);
647+
size_t len = strlen(s) + 1;
648+
char *r = pool_alloc(len);
649+
memcpy(r, s, len);
649650
return r;
650651
}
651652

revision.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ char *path_name(const struct name_path *path, const char *name)
3838
}
3939
n = xmalloc(len);
4040
m = n + len - (nlen + 1);
41-
strcpy(m, name);
41+
memcpy(m, name, nlen + 1);
4242
for (p = path; p; p = p->up) {
4343
if (p->elem_len) {
4444
m -= p->elem_len + 1;

0 commit comments

Comments
 (0)