compat: helper for detecting unsigned overflow

The idiom (a + b < a) works fine for detecting that an unsigned
integer has overflowed, but a more explicit

	unsigned_add_overflows(a, b)

might be easier to read.

Define such a macro, expanding roughly to ((a) < UINT_MAX - (b)).
Because the expansion uses each argument only once outside of sizeof()
expressions, it is safe to use with arguments that have side effects.

Signed-off-by: Jonathan Nieder <jrnieder@gmail.com>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
This commit is contained in:
Jonathan Nieder
2010-10-10 21:59:26 -05:00
committed by Junio C Hamano
parent a8e4a5943a
commit 1368f65002
4 changed files with 11 additions and 4 deletions

View File

@ -53,7 +53,7 @@ void *xmalloc(size_t size)
void *xmallocz(size_t size)
{
void *ret;
if (size + 1 < size)
if (unsigned_add_overflows(size, 1))
die("Data too large to fit into virtual memory space.");
ret = xmalloc(size + 1);
((char*)ret)[size] = 0;