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 badly.
int main() { int *p; /* wild pointer */ /* Some unknown memory location is being corrupted. This should never be done. */ *p = 12; } |
chevron_right
filter_none
Please note that if a pointer p points to a known variable then it’s not a wild pointer. In the below program, p is a wild pointer till this points to a.
int main() { int *p; /* wild pointer */ int a = 10; p = &a; /* p is not a wild pointer now*/ *p = 12; /* This is fine. Value of a is changed */ } |
chevron_right
filter_none
If we want 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 allocated memory.
int main() { int *p = (int *)malloc(sizeof(int)); *p = 12; /* This is fine (assuming malloc doesn't return NULL) */ } |
chevron_right
filter_none
Recommended Posts:
- Dangling, Void , Null and Wild Pointers
- Why we should avoid using std::endl
- How to avoid Structure Padding in C?
- Memory leak in C++ and How to avoid it?
- What is Memory Leak? How can we avoid?
- Features and Use of Pointers in C/C++
- Applications of Pointers in C/C++
- What are near, far and huge pointers?
- Pointers in C/C++ with Examples
- Pointers vs References in C++
- Smart Pointers in C++
- The length of a string using pointers
- Program to Reverse a String using Pointers
- Pointers in C and C++ | Set 1 (Introduction, Arithmetic and Array)
- C program to sort an array using pointers
Improved By : vishnureddy7



