Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on Why does calloc accept 2 arguments, and with what arguments should one call it?
Post
Why does calloc accept 2 arguments, and with what arguments should one call it?
According to the standard (C17 draft, 7.22.3.2) The function calloc
void *calloc(size_t nmemb, size_t size);
"allocates space for an array of nmemb
objects, each of whose size is size
[and] initialize[s] [...] all bits [to] zero". Like malloc
, it returns a void *
pointer to the allocated space or a null pointer on failure.
Unlike malloc
void *malloc(size_t nbytes);
calloc
takes two arguments. I read that the function signature of calloc
lets a good implementation check for some sort of multiplicative overflow. For example, this manpage states (formatting adapted):
If the multiplication of
nmemb
andsize
would result in integer overflow, thencalloc()
returns an error. By contrast, an integer overflow would not be detected in the following call tomalloc()
, with the result that an incorrectly sized block of memory would be allocated:
malloc(nmemb * size);
But I also heard that its 2-argument function signature is flawed and that the following calls are equivalent:
calloc(1, m*n)
calloc(m, n)
calloc(n, m)
calloc(m*n, 1)
(The last example was added by myself.)
This leads me to ask: Why does calloc
accept 2 arguments, and with what arguments should one call it? Is its function signature designed well?
1 comment thread