C: Why do unassigned pointers point to unpredictable memory and NOT point to NULL?

后端 未结 11 1443
没有蜡笔的小新
没有蜡笔的小新 2020-12-05 04:25

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.

I asked many people in

11条回答
  •  被撕碎了的回忆
    2020-12-05 04:33

    First, forced initialization doesn't fix bugs. It masks them. Using a variable that doesn't have a valid value (and what that is varies by application) is a bug.

    Second, you can often do your own initialization. Instead of int *p;, write int *p = NULL; or int *p = 0;. Use calloc() (which initializes memory to zero) rather than malloc() (which doesn't). (No, all bits zero doesn't necessarily mean NULL pointers or floating-point values of zero. Yes, it does on most modern implementations.)

    Third, the C (and C++) philosophy is to give you the means to do something fast. Suppose you have the choice of implementing, in the language, a safe way to do something and a fast way to do something. You can't make a safe way any faster by adding more code around it, but you can make a fast way safer by doing so. Moreover, you can sometimes make operations fast and safe, by ensuring that the operation is going to be safe without additional checks - assuming, of course, that you have the fast option to begin with.

    C was originally designed to write an operating system and associated code in, and some parts of operating systems have to be as fast as possible. This is possible in C, but less so in safer languages. Moreover, C was developed when the largest computers were less powerful than the telephone in my pocket (which I'm upgrading soon because it's feeling old and slow). Saving a few machine cycles in frequently used code could have visible results.

提交回复
热议问题