Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I say calloc(1000, 23), does the 23 "round up" to 24? Or to 32?

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!

like image 935
user541686 Avatar asked Dec 14 '25 10:12

user541686


2 Answers

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.)

like image 125
Dan Breslau Avatar answered Dec 16 '25 22:12

Dan Breslau


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.

like image 35
AnT Avatar answered Dec 16 '25 22:12

AnT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!