Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new[] expression does not respect alignment in Microsoft VC++

Tags:

c++

visual-c++

If new[] expression is used to create an array of objects having destructors, the objects in the array may not be properly alligned

#include <stdint.h>
#include <stdio.h>

#pragma pack(8)
struct A{
  int64_t i;
  char dummy;
  ~A(){}
};

int main(){
  A* pa= new A[2];
  printf("sizeof(A)= %d, pointer= %p", sizeof(A), pa);
}

(I build 32-bit target with VC++ 2010 express)

The output (on my computer) is:

 sizeof(A)= 16 pointer= 00344f4c

(sizeof(A)= 16 shows that compiler undrstand the alignment requirements for A and the struct is padded with 7 bytes [ edited: __alignof(A) also returns 8 ])

I understand why it happens: new[] needs to store array length and it use for this purpose first 4 bytes of allocated memory, then it allocates the array itself without proper padding.

From a practical viewpoint such a behaviour is definitely poor, but is it standard compliant or not?

like image 239
user396672 Avatar asked Jan 28 '11 11:01

user396672


1 Answers

You should use __declspec for this purpose. Your code generated misaligned objects on my computer too (using VS2010) but when I changed to __declspec(align(8)), the pointers were correctly aligned.

I believe that pragma pack only changes the size of the struct and doesn't make any guarantees about it's location.

like image 104
Puppy Avatar answered Oct 31 '22 18:10

Puppy