Skip to content

Commit

Permalink
add xsnprintf helper function
Browse files Browse the repository at this point in the history
There are a number of places in the code where we call
sprintf(), with the assumption that the output will fit into
the buffer. In many cases this is true (e.g., formatting a
number into a large buffer), but it is hard to tell
immediately from looking at the code. It would be nice if we
had some run-time check to make sure that our assumption is
correct (and to communicate to readers of the code that we
are not blindly calling sprintf, but have actually thought
about this case).

This patch introduces xsnprintf, which behaves just like
snprintf, except that it dies whenever the output is
truncated. This acts as a sort of assert() for these cases,
which can help find places where the assumption is violated
(as opposed to truncating and proceeding, which may just
silently give a wrong answer).

Signed-off-by: Jeff King <peff@peff.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
  • Loading branch information
Jeff King authored and Junio C Hamano committed Sep 25, 2015
1 parent fbe85e7 commit 7b03c89
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
3 changes: 3 additions & 0 deletions git-compat-util.h
Original file line number Diff line number Diff line change
Expand Up @@ -744,6 +744,9 @@ static inline size_t xsize_t(off_t len)
return (size_t)len;
}

__attribute__((format (printf, 3, 4)))
extern int xsnprintf(char *dst, size_t max, const char *fmt, ...);

/* in ctype.c, for kwset users */
extern const unsigned char tolower_trans_tbl[256];

Expand Down
16 changes: 16 additions & 0 deletions wrapper.c
Original file line number Diff line number Diff line change
Expand Up @@ -621,6 +621,22 @@ char *xgetcwd(void)
return strbuf_detach(&sb, NULL);
}

int xsnprintf(char *dst, size_t max, const char *fmt, ...)
{
va_list ap;
int len;

va_start(ap, fmt);
len = vsnprintf(dst, max, fmt, ap);
va_end(ap);

if (len < 0)
die("BUG: your snprintf is broken");
if (len >= max)
die("BUG: attempt to snprintf into too-small buffer");
return len;
}

static int write_file_v(const char *path, int fatal,
const char *fmt, va_list params)
{
Expand Down

0 comments on commit 7b03c89

Please sign in to comment.