简体   繁体   English

内存访问:为什么它不崩溃以及如何执行它?

[英]memory access: why it doesn't crash and how to enforce it?

I expect the following code would generate certain memory access fault but it doesn't. 我希望以下代码会生成某些内存访问错误,但不会。 Is there way to enforce it during compilation? 有没有在编译过程中强制执行的方法?

#include <iostream>
class B {};
class D : public B
{ public: int d; };

using namespace std;

main()
{
    B *pB = new B;
    ((D*)pB)->d = 2;
    cout << ((D*)pB)->d << endl;
}

As I understand, casting pointer to D does not change memory allocation so accessing "d" should be illegal, right? 据我了解,将指针强制转换为D不会更改内存分配,因此访问“ d”应该是非法的,对吗?

Yes, accessing d is illegal, and your code has undefined behaviour. 是的,访问d 非法的,并且您的代码具有未定义的行为。

There is no concept of "crash" in C++, so it does not make sense to ask for a portable way to create a "crash". C ++中没有“崩溃”的概念,因此,要求一种可移植的方式来创建“崩溃”是没有意义的。 If the behaviour of a program is undefined, it is not portable, and the language rules do not tell you what the program is doing. 如果程序的行为是不确定的,则它是不可移植的,并且语言规则不会告诉您程序在做什么。

It is illegal, but you are casting which tells the compiler you know what you are doing (don't do this without knowing the consequences) and cthat converts your pointer from B* to a D* while still actually being a B obhect at the location pointed to. 这是非法的,但是您要进行强制转换,以告知编译器您正在执行的操作(不要在不知道后果的情况下执行此操作),并且c会将指针从B *转换为D *,而实际上仍然是B对象。指向的位置。 So the results here are UNDEFINED since you are accessing out of bounds. 因此,这里的结果是不确定的,因为您访问的是越界。

Also it would be good to prefer C++ style casts, vs C style casts (you are using a C-style cast) as they are generally a bit safer. 相对于C样式转换(您正在使用C样式转换),最好还是使用C ++样式转换,因为它们通常更安全一些。

What you are doing usually won't cause a crash because of the way that memory allocation is typically handled behind the scenes. 由于内存分配通常是在后台处理的,因此您所做的事情通常不会导致崩溃。

And there are third party products that can check for errors of this kind (a buffer overrun in this case). 并且有第三方产品可以检查此类错误(在这种情况下,缓冲区溢出)。 Just search for "memory debuggers c++". 只需搜索“内存调试器c ++”。 Most tools for Windows are commercial, but there may be free ones available. Windows的大多数工具都是商业工具,但可能有免费工具可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM