Open In App
Related Articles

What are Wild Pointers? How can we avoid?

Improve Article
Improve
Save Article
Save
Like Article
Like

Uninitialized pointers are known as wild pointers because they point to some arbitrary memory location and may cause a program to crash or behave unexpectedly.

Example of Wild Pointers

In the below code, p is a wild pointer.

C




// C program that demonstrated wild pointers
int main()
{
    /* wild pointer */
    int* p;
    /* Some unknown memory location is being corrupted.
    This should never be done. */
    *p = 12;
}


How can we avoid wild pointers?

If a pointer points to a known variable then it’s not a wild pointer.

Example

In the below program, p is a wild pointer till this points to a.

C




int main()
{
    int* p; /* wild pointer */
    int a = 10;
    /* p is not a wild pointer now*/
    p = &a;
    /* This is fine. Value of a is changed */
    *p = 12;
}


If we want a pointer to a value (or set of values) without having a variable for the value, we should explicitly allocate memory and put the value in the allocated memory.

Example

C




int main()
{
    int* p = (int*)malloc(sizeof(int));
    // This is fine (assuming malloc doesn't return
    // NULL)
    *p = 12;
}



Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 30 Oct, 2023
Like Article
Save Article
Similar Reads