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 othe
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.
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.
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.
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)
int a,*ptr;
now
print(ptr,*ptr)
In the above code two cases can be possible:
It'll execute if default value in ptr is not the address of some used memory of program.
Output:
ptr *ptr
eg. 0x400730 -1992206795
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.
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.