[NTLUG:Discuss] Processor architecture related queries

kbrannen@gte.net kbrannen at gte.net
Wed Dec 3 19:40:51 CST 2003


Steve Baker wrote:
> Vaidya, Harshal (Cognizant) wrote:
> 
>> To achieve portable code it is specifically mentioned that the 
>> structures in C/C++ should be arranged
> 
>  > in such a way that the objects having larger sizes should be placed 
> prior to the objects having lower
>  > sizes.
> 
> 
> OK - so there are actually two completely separate reasons for doing this.
> 
> The background is that in some architectures, 'int' and 'float' variables
> have to be stored at an address which is an exact multiple of 4, 'short's
> at exact multiples of 2 bytes and 'double's at exact multiples of 8.
> 
> On other platforms, that's not 100% required - but the CPU runs more
> slowly for variables that are not aligned as above.  On these platforms,
> there is typically a compiler option to use padding or strip it out.
> 
> On yet other platforms, it makes no difference whether things are aligned
> or not.
...[a bunch of good stuff snipped]...

In addition to all that, most platforms (but not all) will require the struct 
or union to align on its most restrictive member; the ones that don't require 
that generally require alignment on a 4 byte boundry (there's probably a 
exception to that too. :-)

On one system that I worked on where we played memory manager, we always made 
sure to align all structs on 8 byte boundaries, because at least 1 platform 
that we ported to required it, no matter what was inside.

For stuff like this, you learn to write to the most restrictive platform and 
the rest sort themselves out.  Also, the only way I've ever found to *truly 
know* if your app is portable, is to port it. :-)  Lastly, if you do not own a 
memory checker like PurifyPlus, run (don't walk :-) and get it as quick as you 
can.  It pays for itself many times over.  [And they now have a Linux port!] 
The Gimpel FlexeLint tool is pretty good too.  [Comes as obfucated source, so 
you can run this on Linux.]

HTH,
Kevin




More information about the Discuss mailing list