What are Wild Pointers? How can we avoid?
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
int main()
{
int * p;
*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;
int a = 10;
p = &a;
*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 ));
*p = 12;
}
|
Last Updated :
30 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...