Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am learning C++ and I came to know that pointers if left uninitialized could point to random locations in memory and create problems that memory might be used by some other program.

Now if that is the case we should never have this line in any part of our code:

int* ptr;

Instead we should have something like

int* ptr = NULL; //Is this going to avoid the problem

Please suggest because I have seen the first line(int* ptr;) in many books so I am getting this doubt. If possible give some examples also.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
180 views
Welcome To Ask or Share your Answers For Others

1 Answer

int* ptr = NULL; //Is this going to avoid the problem

This will cause ptr to point to NULL which you can explicitly check for as a default/uninitialized value. It prevents the problem you describe, but a careless programmer can still accidentally dereference a null pointer without checking, causing undefined behaviour.

The main advantage is your convenience for checking whether the ptr has or has not been initialized to anything, ie:

 if (ptr != NULL)
 {
     // assume it points to something
 }

Since this is pretty idiomatic, its pretty dangerous to not initialize the pointer to NULL. The pointer would be initialized to a non-NULL garbage value that doesn't really point to anything real. Worst of all, the check above would pass, causing even worse problems if it just so happens that the address in the pointer is memory you can legally access. In some Embedded environments, you might be able to access any part of memory, so you might accidentally corrupt random parts of memory or random parts of your executing code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...