Versions Compared

Key

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

...

Code Block
bgColor#ccccff
#ifdef WIN32
	#define ALIGN(X)_declspec(align(X))
#elif __GNUC__
	#define ALIGN(X) __attribute__((aligned(X)))
#else
    #define ALIGN(X)
#endif

struct A{
	unsigned long i;
};

struct S{
	unsigned char x;
	ALIGN(4) unsigned char B[sizeof(A)];
}s;


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

Compliant Solution

...

(2)

In the following compliant solution a union is used to impose unsigned long's alignment on the array BVectors provide more safety and modularity than dynamically-allocated arrays

Code Block
bgColor#ccccff
{
  int num = 5;
  if (num * sizeof(SomeClass) > SIZE_MAX) {
    /* handle error */
  }
  vector<SomeClass> sc(num);
  // ...
} // sc automatically deletedstruct 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.

...