summaryrefslogtreecommitdiff
path: root/builtin/blame.c
diff options
context:
space:
mode:
authorJeff King <peff@peff.net>2015-09-24 21:08:12 (GMT)
committerJunio C Hamano <gitster@pobox.com>2015-10-05 18:08:05 (GMT)
commitc7ab0ba3405dc6bc8ade1296ef070a5a89660e76 (patch)
tree547f6b2966c1608b903a1144812aa8b348abba3c /builtin/blame.c
parent6f687c21c07bfb83a63049640cba5fb82c174198 (diff)
downloadgit-c7ab0ba3405dc6bc8ade1296ef070a5a89660e76.zip
git-c7ab0ba3405dc6bc8ade1296ef070a5a89660e76.tar.gz
git-c7ab0ba3405dc6bc8ade1296ef070a5a89660e76.tar.bz2
avoid sprintf and strcpy with flex arrays
When we are allocating a struct with a FLEX_ARRAY member, we generally compute the size of the array and then sprintf or strcpy into it. Normally we could improve a dynamic allocation like this by using xstrfmt, but it doesn't work here; we have to account for the size of the rest of the struct. But we can improve things a bit by storing the length that we use for the allocation, and then feeding it to xsnprintf or memcpy, which makes it more obvious that we are not writing more than the allocated number of bytes. It would be nice if we had some kind of helper for allocating generic flex arrays, but it doesn't work that well: - the call signature is a little bit unwieldy: d = flex_struct(sizeof(*d), offsetof(d, path), fmt, ...); You need offsetof here instead of just writing to the end of the base size, because we don't know how the struct is packed (partially this is because FLEX_ARRAY might not be zero, though we can account for that; but the size of the struct may actually be rounded up for alignment, and we can't know that). - some sites do clever things, like over-allocating because they know they will write larger things into the buffer later (e.g., struct packed_git here). So we're better off to just write out each allocation (or add type-specific helpers, though many of these are one-off allocations anyway). Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Diffstat (limited to 'builtin/blame.c')
-rw-r--r--builtin/blame.c5
1 files changed, 3 insertions, 2 deletions
diff --git a/builtin/blame.c b/builtin/blame.c
index e253ac0..e70fb6d 100644
--- a/builtin/blame.c
+++ b/builtin/blame.c
@@ -459,12 +459,13 @@ static void queue_blames(struct scoreboard *sb, struct origin *porigin,
static struct origin *make_origin(struct commit *commit, const char *path)
{
struct origin *o;
- o = xcalloc(1, sizeof(*o) + strlen(path) + 1);
+ size_t pathlen = strlen(path) + 1;
+ o = xcalloc(1, sizeof(*o) + pathlen);
o->commit = commit;
o->refcnt = 1;
o->next = commit->util;
commit->util = o;
- strcpy(o->path, path);
+ memcpy(o->path, path, pathlen); /* includes NUL */
return o;
}