Wild Pointers in C++

In this tutorial, we are going to learn about Wild pointers in C++. wild pointers are also known as uninitialized pointers, these pointers generally point to some of the arbitrary locations of the memory or may cause the programs to crash or misbehave, they point to some memory location even we don’t know they do not contain the memory location of some valid memory location.

Wild pointers are slightly different from normal pointers i.e. although even wild pointers store the memory addresses but point to some unallocated memory or some arbitrary location or data value. Such pointers are called wild pointers. A pointer might behave like a wild pointer when it is not initialized but it is eventually declared. That is why they point to an arbitrary memory location. The very problem with Wild pointers are that they may cause the programs to crash or misbehave.

How to deal with wild pointers in C++

Look at the C++ code below:

#include <bits/stdc++.h>
using namespace std;

  • We use #include <bits/stdc++.h> because it is the header file that contains every standard library, it is a good practice such a header file because it helps us save time because we do not have to remember every STL of GNU C++ each time for every function.
  • Using namespace std;:- It is used because that out pc knows the code for the cout, cin functionalities.

 

#include <bits/stdc++.h>
using namespace std;
int main() 
{ 
  int *a;  
  *a = 19;  
}
We can see that we are corrupting some unknown memory location hence we need to know that it should not be done.
Here *a is a wild pointer.

How to avoid wild pointers?

We can avoid wild pointers by two methods:

Method1:

We can avoid wild pointers by Initializing them with the address of a variable that is known.

#include <bits/stdc++.h>
using namespace std;
int main() {
   int *a,i;
   for( i=0; i<5 ; i++)
      cout << a[i] << ",";
   return 0;
}

 

Output

7208832 2005885785 3809280 2005885760 7208924

Methods2:

We can avoid wild pointers by Explicitally allocate the memory and put value in the allocated memory.

#include <bits/stdc++.h>
using namespace std;
int main() 
{ 
   int *a = (int *)malloc(sizeof(int)); 
  *a = 19; 
}

Here it is alright since we are assuming malloc doesn’t return NULL.

Leave a Reply

Your email address will not be published. Required fields are marked *