Skip to content

Commit 7b03c89

Browse files
peffgitster
authored andcommitted
add xsnprintf helper function
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 <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent fbe85e7 commit 7b03c89

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

git-compat-util.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -744,6 +744,9 @@ static inline size_t xsize_t(off_t len)
744744
return (size_t)len;
745745
}
746746

747+
__attribute__((format (printf, 3, 4)))
748+
extern int xsnprintf(char *dst, size_t max, const char *fmt, ...);
749+
747750
/* in ctype.c, for kwset users */
748751
extern const unsigned char tolower_trans_tbl[256];
749752

wrapper.c

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -621,6 +621,22 @@ char *xgetcwd(void)
621621
return strbuf_detach(&sb, NULL);
622622
}
623623

624+
int xsnprintf(char *dst, size_t max, const char *fmt, ...)
625+
{
626+
va_list ap;
627+
int len;
628+
629+
va_start(ap, fmt);
630+
len = vsnprintf(dst, max, fmt, ap);
631+
va_end(ap);
632+
633+
if (len < 0)
634+
die("BUG: your snprintf is broken");
635+
if (len >= max)
636+
die("BUG: attempt to snprintf into too-small buffer");
637+
return len;
638+
}
639+
624640
static int write_file_v(const char *path, int fatal,
625641
const char *fmt, va_list params)
626642
{

0 commit comments

Comments
 (0)