41

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.

Michael Myers
  • 188,989
  • 46
  • 291
  • 292
munish
  • 4,505
  • 14
  • 53
  • 83

8 Answers8

49
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.

Ziezi
  • 6,375
  • 3
  • 39
  • 49
Doug T.
  • 64,223
  • 27
  • 138
  • 202
  • 2
    If you do this, it's also important to remember to do it consistently by setting to NULL again when the pointer is deallocated. Otherwise you can't safely assume a non-NULL pointer is dereferenceable. – Rune Aamodt May 03 '11 at 13:26
  • So @Doug you mean int* ptr; should never be used? but @Sasquiha writes that its safe untill we do not dereference it. – munish May 03 '11 at 13:26
  • @munish, Yes its safe if you never dereference it but whats the point of a pointer if you never dereference it? – Doug T. May 03 '11 at 13:27
  • Hmm i am getting your point but I was thinking.If you consider an example in which there is a line in my code int* ptr; and then i dereference it 100 0r 1000 lines later then in the mean while i.e between the time it reaches the 1000th line it should be pointing to a random location.it will be dereferenced a lot later. – munish May 03 '11 at 13:33
  • Where does this garbage value come from though? Does the compiler randomly give this value? – heretoinfinity Dec 29 '21 at 23:40
12

Always initialize your variables.

Occasionally, you may want to initialize to NULL, but most of the time, you should be able to initialize the pointer to the value it is supposed to hold. Declare variables as late as possible, and initialize them at that point, not 15 lines further down in your code.

jalf
  • 243,077
  • 51
  • 345
  • 550
  • One of the main reason that people want to use pointers is because they want to have a handle to something and be able to see if that something exists (by checking for NULL). If you can initialize when declaring the variable, why not just allocate the thing on the stack and be done with it? – Doug T. May 03 '11 at 13:31
  • @Doug: typically because you need it to outlive the current scope. And I don't really see how checking handles for NULL changes anything. In that case you should *also* declare it as late as possible, and try to initialize it immediately. – jalf May 03 '11 at 14:49
6

The line:

int* ptr;

is definitely not guaranteed to initialize the pointer value to anything in particular. The line:

int* ptr = NULL;

Will initialize the pointer to point to address zero, which in practice will never hold anything useful, and which will be conventionally checked for as an invalid pointer value.

Of course, it is still possible, as has been said by Doug T., to attempt to use this pointer without checking it and so it would crash all the same.

Explicitly initializing to NULL has the advantage of ensuring that dereferencing the pointer before setting it to something useful will crash, which is actually a good thing, because it prevents the code from "accidentally" working while masking a serious bug.

DataGraham
  • 1,625
  • 1
  • 16
  • 20
3

It's alway better to initialize a pointer to NULL if for any reason you can't initialize it while declaration occurs . For example:

Object *ptr = new Object();

Typically a function can check the value of the pointer against NULL to verify that the pointer has been initialized before. If you haven't set it explicitly to NULL, and it points to a random value, then it could be dereferenced causing a segfault.

Heisenbug
  • 38,762
  • 28
  • 132
  • 190
  • 1
    It's always better to initialize a pointer. But it's not always better to initialize it to NULL. If you know what value it should have, initialize it to that value directly. – jalf May 03 '11 at 13:26
2

C++ follow on from C in that it is not designed to be a safe; it is designed to be efficient. It is therefore for this reason that automatic variables are not initialized. It is up to you to ensure that no pointer is used before it is initialized (although many compiler will warn you if you don't initialize your variables)

doron
  • 27,972
  • 12
  • 65
  • 103
1
int a,*ptr;

now

print(ptr,*ptr)

In the above code two cases can be possible:

  1. It'll execute if default value in ptr is not the address of some used memory of program.

    Output:

           ptr             *ptr
    eg.  0x400730       -1992206795
    
  2. It'll give error (segmental fault) if default address in the ptr is the address of some used memory of program. E.g. if the address of variable a in the memory is also 0x400730.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Shubhay
  • 11
  • 1
1

If the pointer is not used, the compiler will simply ignore it. Initializing it to NULL is the safe thing to do, imho.

Are you sure your not confusing with a function declaration? It's very common for a function to be declared as

char* do_something(const char* one,const char* two);

In this case, the pointers are used to specify what kind of argument you want to pass.

Jeroen Baert
  • 1,273
  • 2
  • 12
  • 28
-1

In C++, you should generally avoid plain old pointers altogether. Standard library classes, smart pointers (until C++0x only in various libraries like Boost or Loki) and references can and should be used in most places instead.

If you can't avoid pointers, it's indeed preferable to declare them with initializations, which in most cases should not be NULL, but the actual target value, because in C++ you can mix declarations and expressions freely, so you can and should only declare the variable at the point you have meaningful value for it.

That's not the case with C where you have to use pointers a lot and all variables have to (or had to before C99; I am not exactly sure) be declared at the begining of a scope. So many people still have bad habits from C that are not appropriate for C++.

Jan Hudec
  • 73,652
  • 13
  • 125
  • 172
  • 6
    This is simply false. Plain old pointers are still the most common type in well written C++. And while you're correct that you should initialize the pointer with its final value if possible, one possible reason for using a pointer is precisely that you might not be able to do so, and have to set it later. (Otherwise, you would need a reference.) – James Kanze May 03 '11 at 14:11