3 ms·
another thing is that both calloc and malloc return non null pointer for zero arguments (that can be very bad). my_alloc should check for zero size arguments an
by MichaelMoser123 11y ago
another thing is that both calloc and malloc return non null pointer for zero arguments (that can be very bad). my_alloc should check for zero size arguments and return NULL in this case. (The problem is that if your size computation overflowed then you will get a very small non null memory block - which you will be very likely to overwrite)
Calloc has another benefit: if you calculate size by n * sizeof(kuku) then it will detect integer overflow (this can be very important for security sensitive stuff that deals with untrusted input), if you did the computation before that and passed calloc( size, 1) then this multiplication and check is another few cycles wasted.
I wonder if they could have done a standard library allocation function like calloc that does the multiplication with overflow detection, does not zero out memory and that returns NULL on zero arguments - but that would be too much to ask.
- MichaelMoser123 11y agoactually openbsd has something like this: mallocarray [1] and reallocarray [2] (OMG realloc) actually here [3] they say that use of these function in libressl and the openbsd port of the http server, etc. [1] http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man9/mallocarray.9 http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man9/... [2] http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man3/calloc.3?query=reallocarray&arch=i386 http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man3/... [3] http://www.openbsd.org/papers/httpd-asiabsdcon2015.pdf http://www.openbsd.org/papers/httpd-asiabsdcon2015.pdf