Mohamed Oussous
Mohamed Oussous

Reputation: 3

is deleting a variable allocated in heap using void pointer a bad thing?

is there a problem with this code? I mean the delete statement.

int *x = new int;

*x = 13;

void *ptr = x;

delete (int *)ptr;

Upvotes: 0

Views: 148

Answers (3)

JaMiT
JaMiT

Reputation: 17007

Even though you are using an explicit type conversion, the rules for static_cast apply. The relevant rule is in point 10 of the static_cast page @ cppreference.com:

Conversion of any pointer to pointer to void and back to pointer to the original (or more cv-qualified) type preserves its original value.

In your case, you started with a pointer-to-int. You converted that to pointer-to-void when you initialized ptr. You converted back to pointer-to-int in the delete statement. This preserves the original value, meaning that both (int *)ptr and x evaluate to the same address (and have the same type), hence

delete (int *)ptr;

and

delete x;

are equivalent. (I'd also add

delete static_cast<int*>(ptr);

to the list since getting in the habit of using static_cast et al. instead of a C-style cast could save you headaches in the future.)

Upvotes: 2

HAL9000
HAL9000

Reputation: 2188

You are not calling delete on a void pointer in your code. You are turning it back to int * before deleting.

Doing the conversions int * -> void * -> int * is guaranteed to give back the original value of the int pointer. So you are basically calling delete on the same value returned by new. Which is what you are suppose to do.

The issue would be different if you did

int *x = new int;
void *ptr = x;
delete ptr;

Here delete doesn't know that ptr is actually supposed to point to an int, and has no way of calling any destructors belonging to int. In the case of int the destructors probably doesn't do anything, so I can't say fore sure that the code is invalid, maybe someone more versed in c++ could chip in? But for other datatypes with real destructors, that would definitely be an issue.

A small comment at the end: Avoid new/delete. Use smart pointers and container classes. Only use new/delete as exercise on how to write smart pointers.

Upvotes: 1

NeonFire
NeonFire

Reputation: 186

there is nothing wrong with this code, all the memory allocated on the heap is free'd, whether you delete ptr or x but not both. Both pointers point to the same address in memory so this is entirely okay; it is safe bet to set free'd pointers = 0 as well!

#include <iostream>
int main()
{

  int* x = new int;
  *x = 13;
  void* ptr = x;

  std::cout << ptr << '\n'; //prints same address
  std::cout << x << '\n'; //prints same address
  
  delete (int*)ptr;
  //delete x;

  ptr = 0;

}

Upvotes: 0

Related Questions