Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling delete on address of variable

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)

like image 264
user1234567 Avatar asked Dec 22 '14 18:12

user1234567


1 Answers

Your original version does not assign i to an address. It allocates a new int on the heap and initializes its value to 5, then copies that value into i which is on the stack. The memory that you allocated (new'ed) is inaccessible and gets leaked.

The reference version works because i refers to the otherwise-anonymous new'ed memory. Hence &i gives the heap address. In your first version, &i gives the address of the stack variable, not the heap memory, and deleting stack memory is bad news.

like image 77
Andrew Lazarus Avatar answered Sep 19 '22 07:09

Andrew Lazarus