Question

I was wondering, do most implementations of calloc treat the size as an alignment too, and round it up to the next supported granularity?

If so, then do they round up to the next power of 2, or do they round to the next multiple of 8 or 16?

If calloc keeps the parameter the same, then how does that even work? Wouldn't your data then be unaligned?

Thank you!

Was it helpful?

Solution

sizeof is defined to yield the size of an object within an array -- in other words, it already accounts for any padding that's needed for proper alignment. So if sizeof(foo) is 23 for some object foo, then your processor must be byte-aligned. (On the other hand, if you're passing 23 because you just think it's a good value to pass in, then good luck to you; you're on your own.)

OTHER TIPS

As far as alignment is concerned, calloc(1000, 23) is precisely equivalent to malloc(1000 * 23). If the implementation decides to "align" the size in some way, it will snap the total size of 23000 to some greater implementation-defined value. There's no special treatment applied to the second parameter of calloc (or to the first, for that matter).

Snapping 23 to 24 in calloc(1000, 23) would really mean snapping 23000 to 24000 (in terms of total size). There's no reasonable practical implementation that would require adding the entire 1000 for alignment purposes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top