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

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

问题描述

#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 的几率很低;它甚至可能是 trap表示形式(一种与该类型的合法值不对应的位模式).

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天全站免登陆