Computer >> Computer tutorials >  >> Programming >> C programming

Is it safe to delete a void pointer in C/C++?


Void pointer is a pointer which is not associate with any data types. It points to some data location in storage means points to the address of variables. It is also called general purpose pointer.

It is not safe to delete a void pointer in C/C++ because delete needs to call the destructor of whatever object it's destroying, and it is impossible to do that if it doesn't know the type.

Here is a simple example of void pointer −

Example

#include<stdlib.h>
int main() {
   int a = 7;
   float b = 7.6;
   void *p;
   p = &a;
   printf("Integer variable is = %d", *( (int*) p) );
   p = &b;
   printf("\nFloat variable is = %f", *( (float*) p) );
   return 0;
}

Output

Integer variable is = 7
Float variable is = 7.600000