Skip to content

Commit eddda37

Browse files
peffgitster
authored andcommitted
convert strncpy to memcpy
strncpy is known to be a confusing function because of its termination semantics. These calls are all correct, but it takes some examination to see why. In particular, every one of them expects to copy up to the length limit, and then makes some arrangement for terminating the result. We can just use memcpy, along with noting explicitly how the result is terminated (if it is not already obvious). That should make it more clear to a reader that we are doing the right thing. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 02e32b7 commit eddda37

File tree

3 files changed

+4
-4
lines changed

3 files changed

+4
-4
lines changed

builtin/help.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ static void add_man_viewer(const char *name)
176176
while (*p)
177177
p = &((*p)->next);
178178
*p = xcalloc(1, (sizeof(**p) + len + 1));
179-
strncpy((*p)->name, name, len);
179+
memcpy((*p)->name, name, len); /* NUL-terminated by xcalloc */
180180
}
181181

182182
static int supported_man_viewer(const char *name, size_t len)
@@ -192,7 +192,7 @@ static void do_add_man_viewer_info(const char *name,
192192
{
193193
struct man_viewer_info_list *new = xcalloc(1, sizeof(*new) + len + 1);
194194

195-
strncpy(new->name, name, len);
195+
memcpy(new->name, name, len); /* NUL-terminated by xcalloc */
196196
new->info = xstrdup(value);
197197
new->next = man_viewer_info_list;
198198
man_viewer_info_list = new;

fast-import.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -703,7 +703,7 @@ static struct atom_str *to_atom(const char *s, unsigned short len)
703703

704704
c = pool_alloc(sizeof(struct atom_str) + len + 1);
705705
c->str_len = len;
706-
strncpy(c->str_dat, s, len);
706+
memcpy(c->str_dat, s, len);
707707
c->str_dat[len] = 0;
708708
c->next_atom = atom_table[hc];
709709
atom_table[hc] = c;

tag.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ int parse_tag_buffer(struct tag *item, const void *data, unsigned long size)
8282
nl = memchr(bufptr, '\n', tail - bufptr);
8383
if (!nl || sizeof(type) <= (nl - bufptr))
8484
return -1;
85-
strncpy(type, bufptr, nl - bufptr);
85+
memcpy(type, bufptr, nl - bufptr);
8686
type[nl - bufptr] = '\0';
8787
bufptr = nl + 1;
8888

0 commit comments

Comments
 (0)