Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In the following compliant solution a union is used to impose unsigned long's alignment on the array B

Code Block
bgColor#ccccff
{
  struct A{
	unsigned long i;
};

union AlignedUnion{
	unsigned char B[sizeof(A)];

private:
	unsigned long _align_;
}algn;

int main()
{
	A *a = new(&algn.B[0]) A;
	unsigned long val = 0xaabbccdd;
	a->i = val;
	return (0);
}

  

Compliant Solution (1)

The following is a compliant solution on a IA32 system using either GCC or Microsoft's Visual Studio. In this solution the macro ALIGN was added to ensure alignment when compiling with both Microsoft VS compiler and g++ . The ALIGN macro calls either _declspec(align(#)) or _attribute_((aligned(#)))) to enforce alignment on a particular variable. In this case it is used on B to make it aligned to 4, which is the alignment restriction for unsigned long.

 

 

Compliant Solution (2)

In the following compliant solution a union is used to impose unsigned long's alignment on the array B.

Risk Assessment

Accessing a misaligned object may cause the program to terminate abnormally on several systems.

...