简体   繁体   English

*(volatile unsigned int *)的含义0x00 = 0x00;

[英]Meaning of *(volatile unsigned int *) 0x00 = 0x00;

What is the meaning of the following line of code? 以下代码行的含义是什么?

*(volatile unsigned int *) 0x00 = 0x00;

It is used in Assert definition: 在断言定义中使用:

void Assert()
{
    // (some other code above)

    *(volatile unsigned int *) 0x00 = 0x00;

    return;
}

I can guess it is trying to cause the program to crash with a segmentation fault or something similar. 我可以猜测它正在试图导致程序因分段错误或类似原因而崩溃。

Whoever wrote the code was thinking "I hope the compiler does not optimize this crash away, so let's put a volatile in front of the pointer dereference". 编写该代码的人都在想:“我希望编译器不会优化崩溃,所以让我们在指针取消引用之前放置一个volatile”。

But all the code is doing is causing undefined behavior that is not guaranteed to crash. 但是所有代码正在做的事情会导致无法保证的崩溃行为。

An std::terminate() is a much better option if you want your program to terminate then that UB Assert() 如果您希望程序终止,那么std::terminate()是一个更好的选择,那么UB Assert()

Also note that an assert should be given a condition, and then if the condition is false the assert should trigger some failure code. 还要注意,应该给断言一个条件,然后,如果条件为假,则该断言应该触发一些失败代码。 Ot is not meant to be an "exit this program" function. Ot并非要成为“退出此程序”功能。 See linked comment 查看链接的评论

Cast 0x00 to pointer to volatile unsigned int and then dereference it with operator * and write to that address 0x00. 将0x00强制转换为指向volatile unsigned int指针,然后用运算符*取消引用,然后写入该地址0x00。 Which is undefined behavior and on most systems will cause crash. 这是未定义的行为,并且在大多数系统上会导致崩溃。

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

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