allocator_test.cpp (1187B)
1 #include <cstdio> 2 #include <cstdlib> 3 4 #define _ALIGN_ 64 5 6 struct BadObject_t { 7 char buf[57]; // 57 byte buffer 8 }; 9 10 struct NiceObject_t { 11 char buf[57]; // 57 byte buffer 12 char pad[7]; // 7 byte padding 13 }; 14 15 void testAddress(void *base, 16 const size_t align_at, 17 const char *msg, 18 const size_t size) 19 { 20 printf("%s [%lu]: misaligned by %lu bytes\n", 21 msg, 22 size, 23 reinterpret_cast<size_t>(base) % align_at); 24 } 25 26 template <typename T> 27 void testAlignment() 28 { 29 constexpr size_t size = sizeof(T); 30 31 // C++ way 32 T *p = new T[2]; 33 testAddress(&p[0], _ALIGN_, "p[0]", size); 34 testAddress(&p[1], _ALIGN_, "p[1]", size); 35 delete[] p; 36 37 // C way 38 p = reinterpret_cast<T *>(malloc(2 * size)); 39 testAddress(&p[0], _ALIGN_, "p[0]", size); 40 testAddress(&p[1], _ALIGN_, "p[1]", size); 41 free(p); 42 43 // POSIX memalign way 44 posix_memalign((void **)&p, _ALIGN_, 2 * size); 45 testAddress(&p[0], _ALIGN_, "p[0]", size); 46 testAddress(&p[1], _ALIGN_, "p[1]", size); 47 free(p); 48 } 49 50 int main() 51 { 52 testAlignment<BadObject_t>(); 53 testAlignment<NiceObject_t>(); 54 return 0; 55 }