Hacker News new | ask | show | jobs
by loeg 1115 days ago
Multiplying array length by sizeof(element type) can overflow.

Of course, you can write your own malloc_array() that uses __builtin_mul_overflow() and doesn't come with calloc's drawback (the cost of zeroing the allocated memory).

1 comments

OpenBSD's libc has reallocarray for this, which is realloc with the same bounds checking as calloc, but if the first parameter is NULL, it's just calloc without the zeroing.

And I believe you'll find it in glibc too these day? Or if not, there's always libbsd, which has lots of handy stuff anyways.

Yep, good point.