What are wild pointers in C?
Uninitialized pointers are known as wild pointers. The behavior of uninitialized pointers is undefined because they point to some arbitrary memory location. Wild pointers may cause a program to crash or behave badly.
Note: Generally, compilers warn about the wild pointer.
int *ptr; //ptr is wild pointer
Let see a program to understand the wild pointer.
#include<stdio.h> int main() { //ptr pointing some unknown memory location int *ptr; /* wild pointer */ //Assigning value *ptr = 12; printf("%d\n",*ptr); return 0; }
Output:
Undefined behavior.
Explanation: In the mentioned program ptr is not initialized by valid memory. So it might point to an unknown location when you will access the unknown location program behavior will be undefined.
How can we avoid wild pointers?
We can easily avoid the creation of the wild pointer in our program. We must initialize the pointer with some valid memory at the time of the pointer declaration. Let see an example C program,
#include<stdio.h> int main() { int data = 27; //Now pointer pointing valid memory int *ptr = &data; /* no more wild pointer */ //Assigning value *ptr = 12; printf("%d\n",*ptr); return 0; }
Output:
12
Explanation: ptr is pointing to data, so now ptr is not a wild pointer.
If you don’t have a variable, then you can use memory management functions(malloc, calloc, etc) to assign a valid memory. Let see an example,
#include<stdio.h> #include<stdlib.h> int main() { //Now pointer pointing valid memory int *ptr = malloc(sizeof(int)); /* no more wild pointer */ if(ptr == NULL) { return -1; } //Assigning value *ptr = 12; printf("%d\n",*ptr); free(ptr); //free allocated memory return 0; }
Output;
12
finally, if you don’t want to assign memory to the pointer at the time of declaration. You must initialize the pointer with NULL (null pointer). The behavior of the null pointer is defined by C standard and you must validate the pointer before its use.
#include<stdio.h> #include<stdlib.h> int main() { int *ptr = NULL; /* no more wild pointer */ if(ptr == NULL) { ptr = malloc(sizeof(int)); if(ptr == NULL) { return -1; } //Assigning value *ptr = 26; printf("%d\n",*ptr); free(ptr); //free allocated memory } return 0; }
Output;
26
Recommended Articles for you:
- Dangling, Void, Null and Wild Pointers
- Pointer Interview Questions in C/C++.
- Function pointer in c, a detailed guide
- How to create dynamic array in C?
- 15 Common mistakes with memory allocation.
- How to access 2d array in C?
- A brief description of the pointer in C.
- How to use the structure of function pointer in c language?
- 100 C interview questions, your interviewer might ask.
- Memory Layout in C.
- Python Interview Questions with Answer.
- File handling in C.
- Function pointer in structure.
- void pointer in C, A detail discussion.
- File handling in C.
- C format specifiers.