Why aren't pointers initialized with NULL by default?


Can someone please explain why pointers aren't initialized to NULL?

  void test(){
     char *buf;
     if (!buf)
        // whatever

The program wouldn't step inside the if because buf is not null.

I would like to know why, in what case do we need a variable with trash on, specially pointers addressing the trash on the memory?

6/29/2017 9:16:02 AM

Accepted Answer

We all realize that pointer (and other POD types) should be initialized.
The question then becomes 'who should initialize them'.

Well there are basically two methods:

  • The compiler initializes them.
  • The developer initializes them.

Let us assume that the compiler initialized any variable not explicitly initialized by the developer. Then we run into situations where initializing the variable was non trivial and the reason the developer did not do it at the declaration point was he/she needed to perform some operation and then assign.

So now we have the situation that the compiler has added an extra instruction to the code that initializes the variable to NULL then later the developer code is added to do the correct initialization. Or under other conditions the variable is potentially never used. A lot of C++ developers would scream foul under both conditions at the cost of that extra instruction.

It's not just about time. But also space. There are a lot of environments where both resources are at a premium and the developers do not want to give up either.

BUT: You can simulate the effect of forcing initialization. Most compilers will warn you about uninitialized variables. So I always turn my warning level to the highest level possible. Then tell the compiler to treat all warnings as errors. Under these conditions most compilers will then generate an error for variables that are un-initialized but used and thus will prevent code from being generated.

6/25/2017 1:43:05 AM

Quoting Bjarne Stroustrup in TC++PL (Special Edition p.22):

A feature's implementation should not impose significant overheads on programs that do not require it.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow