-5

From Wikipedia:

malloc() does not initialize the memory allocated, while calloc() guarantees that all bytes of the allocated memory block have been initialized to 0.

I understand that malloc doesn't initialize the memory to anything, but I have to wonder, why is this the case? Was there a specific reason behind this design decision? It seems like a bit of an antipattern to use calloc(sizeof(T), 1) in my humble opinion and I want to understand the intention.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
user852541
  • 75
  • 8
  • 10
    Why zero it if the app knows it will immediately fill it with something else? That's just wasted cycles. So having the option to do either seems very defensible/sensible. – kaylum Aug 13 '21 at 02:51
  • When `malloc` was invented, the CPU's of the day were something like 1,000 times slower than we're used to today. Efficiency mattered in a way it doesn't today. Zeroing out malloc'ed memory every time would have taken significant time, time that was usually wasted if the memory was about to be filled in with something else. – Steve Summit Aug 13 '21 at 03:17

1 Answers1

2

Because we really don't want to waste all that CPU. It's sooo expensive.

Yes really. You're going to overwrite it anyway.

Joshua
  • 40,822
  • 8
  • 72
  • 132