+ 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.

10th Jan 2019, 3:22 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 odpowiedzi
+ 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.
10th Jan 2019, 4:01 AM
Schindlabua
Schindlabua - avatar
+ 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
10th Jan 2019, 5:19 AM
Schindlabua
Schindlabua - avatar
0
just a thought... is there any way to identify from pointer itself whether it was allocated using new or malloc ?
10th Jan 2019, 4:54 AM
Ketan Lalcheta
Ketan Lalcheta - avatar