C:为什么未分配的指针指向未predictable内存和不点为NULL? [英] C: Why do unassigned pointers point to unpredictable memory and NOT point to NULL?

查看:133
本文介绍了C:为什么未分配的指针指向未predictable内存和不点为NULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很久很久以前我曾经用C编程学校。我记得的东西,我真的很痛恨C:未分配的指针不指向NULL

A long time ago I used to program in C for school. I remember something that I really hated about C: unassigned pointers do not point to NULL.

我问过很多人,包括教师为什么在世界上他们会因为它似乎更危险的它是联合国predictable一个未分配的指针在默认行为不指向NULL

I asked many people including teachers why in the world would they make the default behavior of an unassigned pointer not point to NULL as it seems far more dangerous for it to be unpredictable.

答案是假想的性能,但是我从来不买了。我觉得在编程的历史上有许多许多错误本来是可以避免处于C默认为NULL。

The answer was supposedly performance but I never bought that. I think many many bugs in the history of programming could have been avoided had C defaulted to NULL.

下面一些C code指出的(双关语意)我所讲的:

Here some C code to point out (pun intended) what I am talking about:

#include <stdio.h>

void main() {

  int * randomA;
  int * randomB;
  int * nullA = NULL;
  int * nullB = NULL;


  printf("randomA: %p, randomB: %p, nullA: %p, nullB: %p\n\n", 
     randomA, randomB, nullA, nullB);
}

它与警告编译

(其高兴看到C编译器时相比,我在学校更漂亮)和输出:

Which compiles with warnings (Its nice to see the C compilers are much nicer than when I was in school) and outputs:

randomA:0xb779eff4,randomB:0x804844b,法:(无),nullB:(无)

randomA: 0xb779eff4, randomB: 0x804844b, nullA: (nil), nullB: (nil)

推荐答案

实际上,这取决于指针的存储。与静态存储指针initizalized与空指针。具有自动存储时间指针不会被初始化。见ISO C 99 6.7.8.10:

Actually, it depends on the storage of the pointer. Pointers with static storage are initizalized with null pointers. Pointers with automatic storage duration are not initialized. See ISO C 99 6.7.8.10:

如果具有自动存储时间的对象没有明确初始化,其值为
  不定。如果具有静态存储持续时间不明确初始化的对象,
  那么:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:


      
  • 如果有指针类型,它被初始化为空指针;

  •   
  • ,如果它有算术类型,它被初始化为(正或无符号的)
      零;

  •   
  • ,如果它是一个聚合,每件被初始化(递归的)
      根据这些规则;

  •   
  • 如果它是一个联盟,首批命名成员被初始化(递归)
      根据这些规则。

  •   

是的,具有自动存储持续时间对象未初始化的性能的原因。试想一下初始化在每次调用一个4K阵列记录功能(这是我的一个项目我从事看到,幸运的是Ç让我避免了初始化,产生了很好的性能提升)。

And yes, objects with automatic storage duration are not initialized for performance reasons. Just imagine initializing a 4K array on every call to a logging function (something I saw on a project I worked on, thankfully C let me avoid the initialization, resulting in a nice performance boost).

这篇关于C:为什么未分配的指针指向未predictable内存和不点为NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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