4 ms·
One of the most important reasons to use calloc, other than the zeroing of the allocated memory, is the fact that it checks for integer overflows (at least on m
by Anilm3 11y ago
One of the most important reasons to use calloc, other than the zeroing of the allocated memory, is the fact that it checks for integer overflows (at least on most implementations).
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.
- xcgvgh 11y agoUsing calloc instead of malloc, just for checking arithmetic overflow, is superfluous. You can always write a check or a wrapper for malloc that does that automatically. It is so easy I can write it here: _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.)
- Anilm3 11y agoAgreed, but there's little point in reinventing the wheel in this particular case.
- xcgvgh 11y agoThere is no reinventing going on here. In C you have to write relatively low level code. This includes manually calling allocs for objects, which includes the code for checking your arithmetic. At some point you will have to write that code. If you are smart you will wrap it into a function.
- Anilm3 11y agoI don't see the point of the discussion, that piece of code (or relatively equivalent), is already being performed by a libC function (calloc, in this case), how is that less convenient than you writing it yourself? 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.
- masklinn 11y agoThere's a point to be made that people will be idiots and risk bugs for the sake of efficiency. That's why OpenBSD has reallocarray(3) (which serves as a fine malloc, though the kernel not having reallocation has mallocarray(9))