Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdint>
- using namespace std;
- unsigned char* mem = nullptr;
- struct A
- {
- double d;
- char c[5];
- };
- struct B
- {
- float f;
- int a;
- char c[2];
- double d;
- };
- void InitMemory()
- {
- mem = new unsigned char[1024];
- }
- int main() {
- // your code goes here
- InitMemory();
- //512 byte blocks to write structs A and B to, purposefully misaligned
- unsigned char* memoryBlockForStructA = mem + 1;
- unsigned char* memoryBlockForStructB = mem + 512;
- unsigned char* firstAInMemory = (unsigned char*)(uintptr_t(memoryBlockForStructA) + uintptr_t(alignof(A) - 1) & ~uintptr_t(alignof(A) - 1));
- A* firstA = new(firstAInMemory) A();
- A* secondA = new(firstA + 1) A();
- A* thirdA = new(firstA + 2) A();
- cout << "Alignment of A Block: " << endl;
- cout << "Memory Start: " << (void*)&(*memoryBlockForStructA) << endl;
- cout << "Starting Address of firstA: " << (void*)&(*firstA) << endl;
- cout << "Starting Address of secondA: " << (void*)&(*secondA) << endl;
- cout << "Starting Address of thirdA: " << (void*)&(*thirdA) << endl;
- cout << "Sizeof(A): " << sizeof(A) << endl << "Alignof(A): " << alignof(A) << endl;
- return 0;
- }
- Alignment of A Block:
- Memory Start: 0x563fe1239c21
- Starting Address of firstA: 0x563fe1239c28
- Starting Address of secondA: 0x563fe1239c38
- Starting Address of thirdA: 0x563fe1239c48
- Sizeof(A): 16
- Alignof(A): 8
Add Comment
Please, Sign In to add comment