I assume you're interested in only zeroing out the new part of the array:
Not every memory allocator knows how much memory you're using in an array. for example, if I do:
char* foo = malloc(1);
foo
now points to at least a chunk of memory 1 byte large. But most allocators will allocate much more than 1 byte (for example, 8, to keep alignment).
This can happen with other allocations, too. The memory allocator will allocate at least as much memory as you request, though often just a little bit more.
And it's this "just a little bit more" part that screws things up (in addition to other factors that make this hard). Because we don't know if it's useful memory or not. If it's just padding, and you recalloc
it, and the allocator doesn't zero it, then you now have "new" memory that has some nonzeros in it.
For example, what if I recalloc
foo
to get it to point to a new buffer that's at least 2 bytes large. Will that extra byte be zeroed? Or not? It should be, but note that the original allocation gave us 8 bytes, so are reallocation doesn't allocate any new memory. As far as the allocator can see, it doesn't need to zero any memory (because there's no "new" memory to zero). Which could lead to a serious bug in our code.
calloc()
on the fingers of one hand (without using binary ;-) ), arecalloc()
routine would be only be useful in more extreme corner cases. As such, I think, there is simply no need for it. – Electrothermalrealloc
, followed by amemset
of the "fresh" part of the memory. – Overwordfgets
,strncpy
,atoi
, ...) or misdesigned (scanf
, ...) functions. A lot of functions in the C library are there almost entirely for historic reasons... – Reinforcerecalloc
equivalent tofree
+calloc
or equivalent tocalloc
+memcpy
+free
, that is, should the old contents of the memory be kept or should the whole new size of allocated space be initialized? – Reinforcefree
+calloc
, then I would have just usedfree
+calloc
. – Lyndacalloc()
has another feature thatmalloc()
does not: in arcane systems like DOS: the ability to allocate an array larger thanSIZE_MAX
. Thus code couldcalloc(60000u, sizeof (double))
, even whensize_t
was 16-bit. I have wondered about the C compliance of this - but it appears to be correct. – Hessonrecalloc
was accidentally typed whererealloc
was intended. Two functions with the same signature and extremely similar names, yet massively different functionality is asking for bugs. – Overword