此interpret_cast崩溃的原因
Reason why this reinterpret_cast crashes
背景:我经常处理二进制数据,并且经常需要处理原始指针。我还经常需要这个尺寸,这样我就可以检查我是否读/写了边界(合理,对吧?)。现在,我正试图为指针创建一个语法糖类,该类保存底层数据的大小,以便简化函数声明。
问题的演示-崩溃的类背后的代码可以简化为:
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
我怀疑我违反了严格的混叠规则,但是:
- 我确保使用
char*
作为底层结构。很可能,这并不重要,因为我所说的reinterpret_cast
不是char*
,而是uint32_t*
,编译器不在乎uint32_t*
最初指向的是什么 - 但即使我玩
-fno-strict-aliasing
和-fstrict-aliasing
,程序也会崩溃。。。(我在GNU/Linux下用g++5.2.0编译了这个程序。)
有人能告诉我哪里出了问题吗?我该如何纠正这个问题?
您刚刚在ptr[0]
中存储了1234。然后将1234投射到一个指针中并取消引用它
它试图访问地址1234,但不起作用。
相关文章:
- 当回溯以零开始时,如何调试崩溃
- 如何理解C++标准N3337中的expr.const.cast子句8
- 内联映射初始化的动态atexit析构函数崩溃
- 执行函数时导致崩溃的变量
- 程序崩溃并显示"std::out_of_range"错误
- C++Cast运算符过载
- CoInitialize()在单独的线程上崩溃而不返回
- 使用调试/崩溃报告将应用程序部署到客户端
- 为什么所有C++编译器都会崩溃或挂起此代码
- 为什么lambda在clang上崩溃而不是在gcc上崩溃
- 为什么我的多线程作业队列崩溃
- ExtractIconEx:可以工作,但偶尔会崩溃
- 为什么引用传递会导致此崩溃(C++)
- 试图创建流或fopen时程序崩溃
- 类对象数组的问题会导致崩溃
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 为什么要增加导致崩溃的指针
- 在虚幻引擎中删除NXOpen对象时崩溃
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"