Why can I do:
int i = *(new int (5));
and successfuly use i
after it,
but when I'm trying:
delete &i;
I get a run time error:
Unhandled exception at 0x5ddccaf7 (msvcr100d.dll) in Test.exe: 0xC00000FD: Stack overflow.
If i
was a reference:
int & i = *(new int (5));
, all this (including delete
) works fine.
I know, that it's no good to keep allocated memory handler in something other than pointer and *(new ...)
is awful, but I'm just wondering, why new
works good, but delete
fails.
//Below are just my guesses about the reason of such behavior:
Is it because module which executes program (it's probably not "compiler", because of there is run time already) when it encounters with delete
, it searches for some information like length of data pointing by &i
(in some internal array of such information about all pointers) and don't find it or interpretes some trash data as this information? (I suppose, pointers and references have it, but variables don't)
int i = *(new int (5));
is an instant-memory-leak, right? – Earthenint i = *(new int (5));
, the original pointer to*(new int(5))
is lost andi
is initialized to the value of this expression, which is 5.i
andnew int(5)
are not the same locations, though, which is why you can'tdelete &i
. – Ambiedelete &i;
(not deleting reference, but the data, it's points to) At least, I haven't errors on this line. – Blindagedelete
can only be called on the same pointer as wasnew
'd , or that pointer converted to a base class which has virtual destructor. Other cases are UB. – Maeda