The Wayback Machine - https://web.archive.org/web/20250112115554/https://www.geeksforgeeks.org/what-are-wild-pointers-how-can-we-avoid/
Open In App

What are Wild Pointers? How can we avoid?

Last Updated : 30 Oct, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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;
}



Master C++ with our comprehensive C++ Programming Course Online, perfect for anyone from beginners to advanced learners. Learn everything from the fundamentals to advanced C++ concepts, and apply your knowledge through practical exercises.

Take the Three 90 Challenge! Finish 90% of the course in 90 days, and enjoy a 90% refund. Stay focused, track your progress, and challenge yourself to complete the course! Join today and begin your C++ programming journey!


Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg