Aligning Numerical Data

From InterBase

Go Up to Understanding the XSQLDA


Ordinarily, when a variable with a numeric data type is created, the compiler will ensure that the variable is stored at a properly aligned address, but when numeric data is stored in a dynamically allocated buffer space, such as can be pointed to by the XSQLDA and XSQLVAR structures, the programmer must take precautions to ensure that the storage space is properly aligned.

Certain platforms, in particular those with RISC processors, require that numerical data in dynamically allocated storage structures be aligned properly in memory. Alignment is dependent both on data type and platform.

For example, a short integer on a Sun SPARCstation must be located at an address divisible by 2, while a long on the same platform must be located at an address divisible by 4. In most cases, a data item is properly aligned if the address of its starting byte is divisible by the correct alignment number. Consult specific system and compiler documentation for alignment requirements.

A useful rule of thumb is that the size of a data type is always a valid alignment number for the data type. For a given type T, if size of (T) equals <n>, then addresses divisible by <n> are correctly aligned for T. The following macro expression can be used to align data:

#define ALIGN(ptr, n) ((ptr + n - 1) & ~(n - 1))

where <ptr> is a pointer to char.

The following code illustrates how the ALIGN macro might be used:

char *buffer_pointer, *next_aligned;
next_aligned = ALIGN(buffer_pointer, sizeof(T));

Advance To: