+ 3
Does delete work on pointers other than new operator ?
Below code works without error: void* a; delete a; I thought it fail to compile but no... it compiles perfectly without error.
4 Answers
+ 6
The compiler isn't smart enough to figure out what pointers point to what, so the compiling is fine.
Anyway at runtime it is undefined behaviour (as per 8.3.5.2 in the current draft of the C++ standard), which means we cannot know what it's doing.
I don't know whats going on behind the scenes exactly, but I would guess that as soon as the memory allocator tries to reuse the "free" memory pointed to by `a`, your program would crash.
Probably the program would blow up quicker if you change from `void*` to some class `Foo*`, because then `delete` would try to call a destructor on an object that isn't there.
+ 2
No not really. A pointer is just a number and you have to keep track of what you have malloc'd yourself.
I mean malloc itself must keep track of what it has allocated, so it can free the memory later. So I guess you could... for a single platform... if you have a lot of time...
https://code.woboq.org/userspace/glibc/malloc/malloc.c.html
There's a helpful comment on line 1059. Good luck :P
0
just a thought... is there any way to identify from pointer itself whether it was allocated using new or malloc ?