...
Code Block |
---|
|
int num = 5;
if (num * sizeof(SomeClass) > SIZE_MAX) {
/* handle error */
}
SomeClass *sc = static_cast<SomeClass*>(malloc(sizeof(SomeClass)*num));
if (sc == NULL) {
/* handle error */
}
// initialize sc array
// ...
// destroy sc
free(sc);
|
Compliant Solution
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.
Code Block |
---|
|
#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);
}
|
...