by Anilm3 · 10y ago · 0 comments
For example, when allocating an array of n elements, in malloc you would do something like the following:
ptr = malloc(sizeof(int) * n);
Which could potentially lead to an overflow of the size passed to malloc, hence allocating a significantly smaller buffer and end up accessing adjacent memory which hasn't been allocated to the buffer (buffer overflow)
Calloc requires two arguments, one for size and one for number of elements, which allows it to check for an overflow before performing an allocation (e.g. by using SIZE_MAX):
ptr = calloc(n, sizeof(int));
This is not to say that zeroing memory is not useful. There are many situations in which a zero in a memory block represents the end of the usable data, as for example in a string, so zeroing memory in those situations is definitely recommended.
_Bool Check( const size_t a , const size_t b )
{
if( a > SIZE_MAX / b )
{
return false;
}
return true;
}
(If proper warnings are enabled, it also provides extra integer type checking.)It has nothing to do with how smart you are or how low level C is, you are effectively reinventing that part of calloc by wrapping malloc.