Hacker News new | ask | show | jobs
by JohnFen 1116 days ago
calloc has its own set of gotchas, though. For instance, it may allocate a different amount of memory than you requested, and it comes with the overhead of zeroing out the allocated memory.

Neither of these may matter to you, but when they do, they really matter. So you still have to be thoughtful about using it. Not so different from how you have to be thoughtful about using malloc.

1 comments

I tend to see zeroed memory as an advantage in the vast majority of cases. And when it's actually significant overhead then s/calloc(/reallocarray(NULL,/

The thing I like about almost always allocating through calloc is this: I know that if my code is somehow not initialising memory properly, the resulting bug will be the same each time, and therefore faster to reproduce and debug. Not that I misinitialise my memory very frequently anymore, it's not that hard to get right.

Surprisingly often, I've found that so much of my data should probably default to zero anyway, so it doesn't really matter all that much.

Calloc can over-allocate, which i always found annoying myself, although at least with calloc, you know that if you only index the pointer modulo the n you passed onto calloc, you won't invoke any demons from the underworld.

But yeah, in general, to really know what you're doing in C, you kind of have to understand memory allocators at a fairly deep level, because the footguns are aplenty. You need to have a mental model of the heap and stack.