Wild Pointer In C [Explained With Examples]
Hello friends, in today’s article we are going to talk about Wild Pointer In C Language.
But before knowing about Wild Pointer, I would suggest you that, first know about Null Pointer and Void Pointer because both these concepts will help you to understand Wild Pointer better.
So now without wasting any time let’s understand what is Wild Pointer In C
What is Wild Pointer In C
Definition -: Uninitialized pointers are known as wild pointers because they point to some arbitrary memory location which can cause the program to crash.
In Simple words “a pointer that has not been initialized to anything (not even NULL) is known as a wild pointer.”
Syntax -:
data_type pointer_name;
- data_type -: any data type can come here like int, char, float, etc.
- pointer_name -: Pointer name you can keep anything according to you.
Example -:
int *ptr; //ptr is wild pointer
Here ptr is a wild pointer because it is not initialized with any such value (not even NULL).
Note -: Generally, compilers warn about wild pointers.
Let’s understand the wild pointer by making a program.
Example Program
#include<stdio.h>
void main()
{
//ptr pointing some unknown memory location
int *ptr; /* here ptr is a wild pointer */
//Assigning value
*ptr = 20;
printf("%d\n",*ptr);
}
Output -:
Undefined behavior
Explanation -: In this program, ptr is a wild pointer that has not been initialized with anything. Since it is now pointing to an unknown location, the program displays Undefined behaviour.
How can we avoid wild pointers?
We can easily prevent the creation of wild pointer in our program if it is initialized with some value or any valid memory while declaring the pointer.
Let’s understand these things with a program -:
#include<stdio.h>
void main()
{
int data = 12;
//Now pointer pointing valid memory
int *ptr = &data; /* no more wild pointer */
//Assigning value
*ptr = 20;
printf("%d\n",*ptr);
}
Output -:
20
In this program, the address of the data variable was initialized at the time of declaration to the ptr pointer, so ptr is no longer a wild pointer.
Conclusion
Friends, I hope you have found the answer to your question and you will not have to search about what is Wild Pointer In C and why and how they are used in C language.
However, if you want any information related to this post or related to programming language, or computer science, then comment below I will clear your all doubts
If you want a complete tutorial on C language, then see here C Language Tutorial. Here you will get all the topics of C Programming Tutorial step by step.
Friends, if you liked this post, then definitely share this post with your friends so that they can get information about Wild Pointer In C
To get the information related to Programming Language, Coding, C, C ++, subscribe to our website newsletter. So that you will get information about our upcoming new posts soon.