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

CC++Server Side ProgrammingProgramming

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

 Live Demo

#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
raja
Published on 18-Jun-2019 12:34:27
Advertisements