On Monday 28 November 2005 07:55 am, Dave Smith wrote:
> Indeed, even on modern x86 systems gcc may pad the 1-byte "bool" with 3
> unused bytes to word-align it, especially if it is the last member of a
> struct. Not sure what this would do on a 64-bit system...
>
> For example, unless the -fpack-struct is specified, this structure will
> occupy 8 bytes (as reported by sizeof):
>
> struct {
> int i;
> char c;
> } foo;
>
It gets even better. Since the char* type was historically used to specify a
pointer to void for memory allocation, any malloc() must return a pointer to
a memory region that is properly aligned to store any possible structure.
Eg, on alpha that requires double-word alignment, two consecutive calls to
malloc(1) will return two pointers offset by at least 8 bytes (the 7 in
between are basically wasted).
Last I checked this was the case for both malloc() in c and new char[] in c++.
This allows you to do the following in C++:
char* s = new char[sizeof(MyStruct)];
MyStruct* m = static_cast<MyStruct*>(s);
new (m) MyStruct(<args>); // calls MyStruct's ctor with this == m
--
Respectfully,
Nicholas Leippe
Sales Team Automation, LLC
1335 West 1650 North, Suite C
Springville, UT 84663 +1 801.853.4090
http://www.salesteamautomation.com
/*
PLUG: http://plug.org, #utah on irc.freenode.net
Unsubscribe: http://plug.org/mailman/options/plug
Don't fear the penguin.
*/