Dangling Pointers in C
The most common bugs related to pointers and memory management is dangling/wild pointers. Dangling pointer occurs at the time of the object destruction when the object is de-allocated from memory without modifying the pointer value. The dangling pointer can point to the memory, which contains either the program code or the code of the operating system.
Void Pointers in C
Void pointer is a specific pointer type – void * – a pointer that points to some data location in storage, which doesn’t have any specific type. Void refers to the type.
Important Point
Void pointers cannot be dereferenced. It can however be done using typecasting the void pointer
Null Pointer V/s Void Pointer
Null pointer is specially reserved value of a pointer.
Void pointer is a specific pointer type.
Null pointer suits well for all datatypes.
int, char, float, long, double are all datatypes are supported.
void datatype is alone supported.
Null pointer is used for assigning 0 to a pointer variable of any type.
Void pointer is used for storing address of other variable irrespective of its datatype.
Null Pointer Code:
int main(){
int *p=NULL;
printf("the value inside variable p is:\n%x",p);
return 0;
}
Void Pointer Code:
int main(){
void *p=NULL;
printf("the value inside variable p is:\n%d",sizeof(p));
printf("\nthe value inside variable p is:\n%x",p);
return 0;
}
Wild/Dangling Pointer Code:
int main(){
int *p;
printf("the value inside variable p is:\n%d",*p);
printf("the value inside variable p is:\n%x",p);
return 0;
}
Code with malloc() and free():
int main(){
int *p;
p= malloc(sizeof(int));
if(p!=NULL)
printf("memory created successfully");
return 0;
}