此interpret_cast崩溃的原因

Reason why this reinterpret_cast crashes

本文关键字:崩溃 cast interpret      更新时间:2023-10-16

背景:我经常处理二进制数据,并且经常需要处理原始指针。我还经常需要这个尺寸,这样我就可以检查我是否读/写了边界(合理,对吧?)。现在,我正试图为指针创建一个语法糖类,该类保存底层数据的大小,以便简化函数声明。

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

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("%dn", 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_cast不是char*,而是uint32_t*,编译器不在乎uint32_t*最初指向的是什么
  2. 但即使我玩-fno-strict-aliasing-fstrict-aliasing,程序也会崩溃。。。(我在GNU/Linux下用g++5.2.0编译了这个程序。)

有人能告诉我哪里出了问题吗?我该如何纠正这个问题?

您刚刚在ptr[0]中存储了1234。然后将1234投射到一个指针中并取消引用它

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