解引用NULL指针和未初始化指针之间的差异 [英] Difference between dereferencing NULL pointer and uninitialised pointer

查看:1522
本文介绍了解引用NULL指针和未初始化指针之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码块(C ++)

 #include< bits / stdc ++。 
using namespace std;
int main(){
int * p;
cout<< * p;
}

产生垃圾值,而

 #include< bits / stdc ++。h> 
using namespace std;
int main(){
int * p = NULL;
cout<< * p;
}

会导致运行时错误。
我期望两个运行时错误(ideone产生两个运行时错误),因为这两个都是错误的指针。

解决方案

您对运行时错误的期望有缺陷。



意味着潜在的症状范围:




  • 没有发生任何事情

  • 发生某些情况

  • 发生运行时错误

  • 您的源代码会自动编辑为使用正确的标准标头,而不是误导地黑客实施位


  • 您的猫被杀害

  • 您的猫未被杀害

  • <
  • 您的猫会自杀

  • 您的猫打开一个黑洞

  • 一只猫在黑洞中开启



等等。



这也适用于解除引用NULL,但是现代商品硬件倾向于特别处理NULL解引用,通常保证分段错误有助于诊断。显然,CPU不能为任意指针值,因为它们可以是有效的,只要它知道!


On code blocks(C++)

#include<bits/stdc++.h>
using namespace std;
int main(){
    int *p;
    cout<<*p;
}

produces garbage value, whereas

#include<bits/stdc++.h>
using namespace std;
int main(){
    int *p=NULL;
    cout<<*p;
}

results in runtime error. I expected runtime error for both (ideone produces runtime error for both) because both are bad pointers. How can one explain this?

解决方案

Your expectation of a runtime error is flawed.

Dereferencing an uninitialised/invalid pointer with arbitrary value can do anything at all.

That means the potential symptoms range from:

  • nothing happens
  • something happens
  • a runtime error happens
  • your source code is spontaneously edited to use proper standard headers instead of misguidedly hacking in implementation "bits"
  • your attitude in the comments section is magically improved
  • your cat is murdered
  • your cat is not murdered
  • your cat is murdered and not murdered
  • your cat murders itself
  • a black hole opens inside your cat
  • a cat opens up inside a black hole

and so on.

This is true for dereferencing NULL, too, but modern commodity hardware tends to treat NULL dereferences specially, usually guaranteeing a segmentation fault to aid in diagnostics. Obviously, a CPU cannot do that for arbitrary pointer values, because they may be valid as far as it knows!

这篇关于解引用NULL指针和未初始化指针之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆