Guest User

Untitled

a guest
Apr 24th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdint>
  3. using namespace std;
  4. unsigned char* mem = nullptr;
  5.  
  6. struct A
  7. {
  8. double d;
  9. char c[5];
  10. };
  11.  
  12. struct B
  13. {
  14. float f;
  15. int a;
  16. char c[2];
  17. double d;
  18. };
  19.  
  20. void InitMemory()
  21. {
  22. mem = new unsigned char[1024];
  23. }
  24.  
  25. int main() {
  26. // your code goes here
  27.  
  28. InitMemory();
  29.  
  30. //512 byte blocks to write structs A and B to, purposefully misaligned
  31. unsigned char* memoryBlockForStructA = mem + 1;
  32. unsigned char* memoryBlockForStructB = mem + 512;
  33.  
  34. unsigned char* firstAInMemory = (unsigned char*)(uintptr_t(memoryBlockForStructA) + uintptr_t(alignof(A) - 1) & ~uintptr_t(alignof(A) - 1));
  35. A* firstA = new(firstAInMemory) A();
  36.  
  37. A* secondA = new(firstA + 1) A();
  38. A* thirdA = new(firstA + 2) A();
  39.  
  40. cout << "Alignment of A Block: " << endl;
  41. cout << "Memory Start: " << (void*)&(*memoryBlockForStructA) << endl;
  42. cout << "Starting Address of firstA: " << (void*)&(*firstA) << endl;
  43. cout << "Starting Address of secondA: " << (void*)&(*secondA) << endl;
  44. cout << "Starting Address of thirdA: " << (void*)&(*thirdA) << endl;
  45. cout << "Sizeof(A): " << sizeof(A) << endl << "Alignof(A): " << alignof(A) << endl;
  46. return 0;
  47. }
  48.  
  49. Alignment of A Block:
  50. Memory Start: 0x563fe1239c21
  51. Starting Address of firstA: 0x563fe1239c28
  52. Starting Address of secondA: 0x563fe1239c38
  53. Starting Address of thirdA: 0x563fe1239c48
  54. Sizeof(A): 16
  55. Alignof(A): 8
Add Comment
Please, Sign In to add comment