deleting a void pointer using delete operator [duplicate]

白昼怎懂夜的黑 提交于 2019-12-08 15:33:41

问题


whats wrong with the code. What it should be. As it is throwing an error. Operator 'delete', applied to void* argument.

int i;
void *ptr = &i;

delete ptr;

回答1:


whats wrong with the code.

Everything except int i;

The second line attempts to convert an integer to a pointer. In special circumstances, you could force that past the compiler with reinterpret_cast; but the program would only behave correctly if the integer somehow contained a valid pointer value. (UPDATE: the question has now been edited to take the address of i instead; so this line is no longer wrong).

The third line attempts to delete invalid memory using an invalid pointer type.

What it should be.

Something else. Without knowing what you want to do, it's impossible to say. Perhaps you want:

int i;
void * ptr = &i;  // Points to `i`, losing type information.

Operator delete, applied to void* argument.

That's always wrong. You must only delete an object you previously allocated with new; and the pointer must be to the correct type.

(or to a base class, if it's a class type with a virtual destructor)

So the following would be correct; but pointless unless you have a good reason for dynamic allocation:

int * ptr = new int;
delete ptr;

And of course, if you're writing code that should be robust against memory leaks and runtime errors, you should manage all dynamic memory using RAII types such as containers and smart pointers. So, if you need to a dynamic object, you should do:

std::unique_ptr<int> ptr(new int);

if you want a to delete it at the end of the current scope or move it into another scope; or

auto ptr = std::make_shared<int>();

if you want to share ownership between more than one scope. In either case, the pointers will delete the object automatically once you've finished with it.




回答2:


You should only delete things that you allocated with new.




回答3:


Very naughty code indeed;

  1. You're not taking the address of i; use void* ptr = &i instead. You're compiler is extremely lenient to emit your code.
  2. You're deleting from the stack. Not good. You can only delete things you've newed
  3. The compiler doesn't know how much memory to delete if you pass void* as all the sizeof data are lost.



回答4:


your code will not work because you're trying to delete something which wasn't dynamically allocated.
Anyway deleting void pointers is undefined, see this Q&A for more info



来源:https://stackoverflow.com/questions/16811108/deleting-a-void-pointer-using-delete-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!