对未初始化的指针指向任何地方这一事实感到困惑 [英] Confusion about the fact that uninitialized pointer points to anywhere

查看:35
本文介绍了对未初始化的指针指向任何地方这一事实感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

int main(void)
{
    int *ptr;
    printf("%p", ptr); // Error: uninitialized local variable 'ptr' used
                       // Output is "0"
}

我正在阅读关于空指针的 C-FAQ.它说未初始化的指针可能指向任何地方.这是否意味着它指向内存中的随机位置?此外,如果这个陈述是真的,如果我尝试 printf("%p",ptr) 为什么会发生错误?由于未初始化的指针ptr指向某个随机位置,看来它必须打印出这个随机位置!

I'm reading C-FAQ about null pointer. And it says that uninitialized pointer might point to anywhere. Does that mean it points to random location in memory? Also if this statement is true, why does error occur if i try printf("%p",ptr)? Since uninitialized pointer ptr points to some random location, it seems that it must print out this random location!

推荐答案

未初始化的 auto 变量(指针类型或其他)的内容是不确定的;实际上,它是最后写入该内存位置的任何内容.这种随机位模式对应于程序中有效地址1 的几率非常低;它甚至可能是一个陷阱表示(一种不对应于该类型的合法值的位模式).

The contents of an unitialized auto variable (pointer type or otherwise) are indeterminate; in practice, it's whatever was last written to that memory location. The odds that this random bit pattern corresponds to a valid address1 in your program are pretty low; it may even be a trap representation (a bit pattern that does not correspond to a legal value for the type).

尝试取消引用无效的指针值会导致未定义的行为;任何结果都是可能的.您的代码可能会彻底崩溃,它可能在没有明显问题的情况下运行,它可能会使您的系统处于错误状态.

Attempting to dereference an invalid pointer value results in undefined behavior; any result is possible. Your code may crash outright, it may run with no apparent issues, it may leave your system in a bad state.

<小时>

  1. 即你的程序中定义的对象或函数的地址,或者是用malloc或类似方式分配的动态对象.
  1. That is, the address of an object or function defined in your program, or a dynamic object allocated with malloc or similar.

这篇关于对未初始化的指针指向任何地方这一事实感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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