reinterpret_cast 崩溃的原因

Reason why this reinterpret_cast crashes

背景:我经常使用二进制数据,并且经常需要使用原始指针。我还经常需要大小,以便我可以检查我是否 read/write 越界(合理,对吗?)。现在,我正在尝试为保存基础数据大小的指针创建语法糖 class,以便我可以简化函数声明。

问题演示 - 我的 class 崩溃背后的代码可以简化为:

char *a = (char*) malloc(4); // some underlying data
strncpy(a, "1234", 4); // that is not statically linked so it can be written to

uint32_t *ptr = reinterpret_cast<uint32_t*>(a);

ptr[0] = 1234; // works
reinterpret_cast<int&>(ptr[0]) = 1234; // curiously, this works too
*reinterpret_cast<int*>(ptr[0]) = 1234; // this crashes the program

printf("%d\n", ptr[0]);

如评论所述,上述程序崩溃。 Valgrind 输出如下:

Invalid write of size 4
   at 0x40064A: main (in /home/rr-/test)
 Address 0x4d2 is not stack'd, malloc'd or (recently) free'd

我怀疑我违反了严格的别名规则,但是:

  1. 我确保使用 char* 作为底层结构。最有可能的是,这无关紧要,因为我 reinterpret_casting 不是 char* 而是 uint32_t* 并且编译器不关心 uint32_t* 最初指向的是什么.
  2. 但即使我玩 -fno-strict-aliasing-fstrict-aliasing,程序仍然会崩溃...(我在 GNU/Linux 下使用 g++ 5.2.0 编译程序。)

谁能告诉我哪里出错了,我该如何纠正这个问题?

您刚刚在 ptr[0] 中存储了 1234。然后将 1234 转换为指针并取消引用它。

它试图访问地址 1234,但不起作用。