4 ms·
I always thought it was because of padding. An array of M structures each N bytes long could require more than M*N bytes (certainly has on some architectures I
by notacoward 10y ago
I always thought it was because of padding. An array of M structures each N bytes long could require more than M*N bytes (certainly has on some architectures I've worked with). But I guess that's not it after all.
- to3m 10y agocalloc doesn't know what it's allocating for, so it has to hand out m * n. (Despite the syntax, the same goes for operator new in C++! Placement vector new in particular is a trap.)
- tedunangst 10y agoPadding is included in sizeof.
- mikeash 10y agoC accounts for padding in the size of the individual type. By the time you do sizeof, it's already rounded up to where you can just do M*N. For example: struct S { long a; char b; }; On my computer (64-bit Mac), sizeof(struct S) is 16, due to 7 bytes of padding after b. Since the compiler handles the padding, that means calloc doesn't have to.
- xxpor 10y agoWhich can lead to sadness if you're not careful with #pragma pack and the like.
- notacoward 10y agoToday's compilers. How about the compilers when calloc was first defined? As I said, I've worked on compilers that behaved differently, either always or according to various options. The computing universe has actually become less diverse in some ways than it used to be, so we should be careful of drawing conclusions about old interfaces based on today's monoculture. Is it really impossible for people here to imagine that some of the dozens of platforms that had their own compilers and C libraries chose to do the rounding up in the latter? It would actually be a pretty reasonable choice, for different microarchitectures capable of running the same instruction set and binaries but with different cache subsystems. That way you could make the decision at run time instead of compile time. Many of the early RISC machines did even weirder tricks than that to wring out the last bit of performance on multiple generations without having to recompile.
- stouset 10y agoThis would be very, very bad for performance in a lot of cases do to non-aligned struct reads, were it true.