What are Wild Pointers in C/C++



In C/C++, a wild pointer is a type of pointer that has not been initialized to a valid memory address. It points to memory that has been deallocated and is called a dangling pointer. The pointer behaves like a wild pointer when it is declared but not initialized. That is why, they point to random memory location.

Syntax

The basic syntax of initializing wild pointer in C/C++:

int *ptr;

Example of Wild Pointer

In this example, we create a pointer arr that doesn't assign it any memory. Then, it tries to print 5 values from it using a loop. Since arr is uninitialized, it points to some unknown memory, which can cause errors or unexpected output.

C C++
#include <stdio.h>

int main() {
   int *arr;
   for (int i = 0; i < 5; i++) {
       printf("%d ", arr[i]);
   }
   return 0;
}

Output

The above program generates a random address on every compilation. The output shown here is not fixed.

1215601518 32764 0 0 1215601523 
#include <bits/stdc++.h>
using namespace std;

int main() {
   int *arr;
   for(int i=0; i < 5; i++)
   cout << arr[i] << " ";
   return 0;
}

Output

The above program generates a random address on every compilation. The output shown here is not fixed.

731007854 32764 0 0 731007859 

Explanation of the program:

In the above program, a pointer arr is declared but not initialized. So, it is displaying some random memory locations.

How to Avoid Wild Pointer ?

To avoid the wild pointer, use the following declaration in C/C++:

1. Initialize pointers while declaring

When you create a pointer, also give it a starting value. It helps to avoid errors and keep the program running smoothly.

int z = 0;
int *ptr = &z; 

2. Set the uninitialized pointers to NULL

If you don't give a pointer a value, set it to NULL. This means it points to nothing and helps prevent errors.

int *ptr = NULL;

3. Use dynamic memory allocation

The dynamic memory allocation is useful to get the memory while the program runs. This is helpful when we don't know about the memory size.

int *ptr = (int *)malloc(sizeof(int));
if (ptr != NULL) {
    *ptr = 10;
    free(ptr);
    
    // Avoid dangling pointer
    ptr = NULL; 
}
Updated on: 2025-04-21T18:05:33+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements