why does my program not crash

Jun 8, 2016 at 9:41pm
Hi guys I'm learning about memory,and I was expecting this program to crash as I allocated memory in the heap to a pointer but I then deallocated the memory yet when I do cout << hi; or cout << *hi; the program does not crash how come the program didn't crash like I expected it would?

1
2
3
4
5
6
7
8
9
10
11
12
  #include <iostream>

using namespace std;

int main()
{

   int* hi = new int;
   cout << &hi << endl;
   delete hi;
   cout << *hi;
}
Jun 8, 2016 at 9:44pm
Do you get run over every time you cross the street without looking?
Jun 8, 2016 at 9:50pm
I'm not sure what you mean cire,there's always a chance but it's not guaranteed but how would that be any way related to my program crashing vs not crashing?
Jun 8, 2016 at 9:55pm
Because with undefined behavior there is
adam2016 wrote:
always a chance but it's not guaranteed
that your program might crash.

Jun 8, 2016 at 10:00pm
ohh ok,so that means theres a chance that hi would still be allocated to an address?
Jun 9, 2016 at 4:02am
ohh ok,so that means theres a chance that hi would still be allocated to an address?

I don't know what that means. hi is a pointer. It will always contain an address. It will be "allocated" as long as it is in scope. Whatever it was pointing to stopped existing when you called delete on hi. It is entirely possible, however, that the memory at the address contained by hi still contains the bit pattern that it did before it was deleted.

It is illegal to access it, however, and you certainly couldn't count on that behavior being consistent.

According to the standard, you're in the realm of undefined behavior where anything could happen. The program could crash, nuclear missiles could be launched or nothing might happen but your program continuing innocuously on, biding its time, waiting to bite you on the ass at some point in the not-so-distant future.
Jun 9, 2016 at 4:41am
Would now be a good time to mention that it is best to completely avoid new and delete? They are low level memory management functions. Also avoid raw pointers, there are smart pointers which are much safer to use. But you might not need them for awhile. While I am at it, one doesn't need char arrays, or arrays in general. One can do awesome amounts of stuff just using the STL and not worry about memory management at all.

Hope this helps a bit :+)
Jun 9, 2016 at 5:58pm
thanks guys clears things up abit =)
Topic archived. No new replies allowed.