HomeMiscWhat is a wild pointer?

What is a wild pointer?

by nikoo28
0 comments 2 minutes read

Question: What is a wild pointer in a program?

Uninitialized pointers are known as wild pointers. These are called so because they point to some arbitrary memory location and may cause a program to crash or behave badly.
This can be understood from the below examples.

 int main() { int *p; // wild pointer, some unknown memory location is pointed	*p = 12; // Some unknown memory location is being changed	// This should never be done. } 

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, some unknown memory is pointed	int a = 10;	p = &a; // p is not a wild pointer now, since we know where p is pointing	*p = 12; // This is fine. Value of a is changed } 

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() {	//malloc returns NULL if no free memory was found	int *p = malloc(sizeof(int));	//now we should check if memory was allocated or not	if(p != NULL)	{	*p = 12; // This is fine (because malloc doesn't return NULL)	}	else	{	printf("MEMORY LIMIT REACHED");	} } 

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.AcceptRead More