Previous Topic

Next Topic

Book Contents

Book Index

The 1-byte alignment challenge

One of the more subtile quirks are the so-called "1-byte alignment" requirement.

So what is that ? When you build your application the compiler and linker performs a lot of advanced stuff. One of the tasks is to "layout" the structures and classes you have used. This means that the compiler reserves the need for certain memory allocations when the application is run. The so-called Struct Member Alignment-setting specifies (see how to specify that setting here) how tight the data should be "packed". The reason for this option is that the compiler can select between compact applications where everything is packed as tight as possible - OR - fast applications with high performance. If you accept the default setting of 8 bytes, most processors will process the memory allocations faster than with other settings because of the internal construction of the processor. In other words, this is a classical choice between speed and memory usage.

The problem occur when one part of your application (compiled with one alignment) calls or interacts with another part of your application which is compiled with another alignment. You will instantly have memory overwrites of all kinds!

Why bother at all with this ? The challenge is that Lotus has built the API libraries with 1-byte alignment. This means that your applications are forced to build with 1-byte alignment.

Why Lotus selected to do this has probably something to do with multi platform support, or even a strong with of being memory conservative (I really don't believe this -- if I take a look at the memory usage in the client or server :-)).

If you don't remember to set your project to use this setting, your project might compile just fine. It might even run - for a while. All of sudden thunder strike and your application goes down! And you haven't got a clue! The errors implied by the absence of 1-byte alignment are extremely subtle and hard to catch.

So - ensure that 1-byte alignment is always turned on. Don't forget to check - and recheck :-)

More info on struct member alignment

The intermediate struct members are forced being aligned to entirely fit in 8-byte words possibly creating gaps within the structure. This means that the same structure compiled with different packing settings may have different size altogether.

Example:

struct S { 
	BYTE b1; 
	WORD w; 
	BYTE b2 
	DWORD d; 
	BYTE b3[5] 
	QWORD q; 
}; 

Structure bytes with 8-byte alignment (x is unused byte):

b1 x w w b2 x x x d d d d b3 b3 b3 b3 b3 x x x x x x x q q q q q q q q  

The same structure with 2-byte alignment:

b1 x w w b2 x d d d d b3 b3 b3 b3 b3 x q q q q q q q q 

As you see, the later structure occupies less space. Imagine what happens when your application tries to access the last QWORD !!!

See Also

General quirks you need to be aware of

All components in an application needs the same compiler- and linker settings