fork download
  1. #include <iostream>
  2. #include <cstring>
  3. #include <iomanip>
  4.  
  5. // 打印内存内容的工具函数
  6. void hexdump(const void* addr, size_t len) {
  7. const uint8_t* p = static_cast<const uint8_t*>(addr);
  8. std::cout << "Address | 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n";
  9. std::cout << "---------|------------------------------------------------\n";
  10. for (size_t i = 0; i < len; i += 16) {
  11. std::cout << reinterpret_cast<const void*>(p + i) << " | ";
  12. for (int j = 0; j < 16 && (i + j) < len; ++j) {
  13. std::cout << std::hex << std::setw(2) << std::setfill('0')
  14. << static_cast<int>(p[i + j]) << " ";
  15. }
  16. std::cout << "\n";
  17. }
  18. }
  19.  
  20. int main() {
  21. // 分配两个连续的 8 字节块(0x00~0x07 和 0x08~0x0F)
  22. alignas(8) struct {
  23. uint8_t block1[8]; // 地址 0x00~0x07
  24. uint8_t block2[8]; // 地址 0x08~0x0F
  25. } memory;
  26.  
  27. // 染色内存块
  28. memset(memory.block1, 0xAA, sizeof(memory.block1)); // 块1: 全 0xAA
  29. memset(memory.block2, 0xBB, sizeof(memory.block2)); // 块2: 全 0xBB
  30.  
  31. std::cout << "=== 初始内存状态 ===\n";
  32. hexdump(&memory, 16);
  33.  
  34. // 强制在地址 0x06 写入 int64_t(跨 block1 和 block2)
  35. volatile int64_t* unaligned_ptr = reinterpret_cast<int64_t*>(
  36. reinterpret_cast<uint8_t*>(&memory) + 6
  37. );
  38. *unaligned_ptr = 0x1122334455667788; // 写入测试值
  39.  
  40. std::cout << "\n=== 写入后的内存状态 ===\n";
  41. hexdump(&memory, 16);
  42.  
  43. return 0;
  44. }
Success #stdin #stdout 0s 5312KB
stdin
Standard input is empty
stdout
=== 初始内存状态 ===
Address  | 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
---------|------------------------------------------------
0x7ffeedce5650 | aa aa aa aa aa aa aa aa bb bb bb bb bb bb bb bb 

=== 写入后的内存状态 ===
Address  | 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
---------|------------------------------------------------
0x7ffeedce5650 | aa aa aa aa aa aa 88 77 66 55 44 33 22 11 bb bb