This is supposed to crash...right?

I ran this code through the VC++ debugger to see what would happen. All that happened was nothing...the program continued as normal after this code.
1
2
3
4
5
6
{
	int* a = new int;
	{
		int* b = a;
	}
}//Should explode here, right? 
So my question is, why didn't my computer explode? (not physically, of course)
Last edited on
Upon hitting Line 6, you just have a memory leak (harmless except wasted heap).

On Lines 5 and 6, there is no automatic delete of memory - there is no built-in gc() in C++ (and a decent gc() with correct reference counting still would not delete on Line 5).
Last edited on
Oh, right. I just realized that. I have to stop thinking that I'm using C++0x automatically deleting pointers!

Now, if I deleted b, then deleted a, it would crash then, right?

EDIT: Nope, just an assert failure.
Last edited on
Hmm... ...haven't looked at C++0x recently, but even then, I would expect the gc() to reference-count properly.

Anything less would be disastrous.

Last edited on
I would expect a crash, but I guess it depends on the OS/what safeguards are in place - asserts aren't free, unfortunately.
Last edited on
Now, if I deleted b, then deleted a, it would crash then, right?


It's undefined behavior. But whatever happens its "bad" and you shouldn't do it.

A crash is possible. Heap corruption is possible.


Also C++0x doesn't automatically delete pointers =P

{
int* a = new int;
{
int* b = a;
}
}//Should explode here, right?


To make it "explode" try to reference those a and b at line 6 see how.

1
2
3
4
5
6
7
{
	int* a = new int;
	{
		int* b = a;
	}
}
cout << *a << " " << *b << "\n";
I don't really understand why anyone would expect a crash. sohguanh's example shouldn't even compile since a and b are not in scope for the cout. Even if b was created before the first shown block, there would be no problem since the integer was never destroyed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
I ran this code through the VC++ debugger to see what would happen. All that happened was nothing...the program continued as normal after this code.
1
2
3
4
5
6
	

{
	int* a = new int;
	{
		int* b = a;
	}
}//Should explode here, right?  


So my question is, why didn't my computer explode? (not physically, of course)


Show a complete example that compiles. The only thing that I see is a memory leak. a and b are destroyed automatically after the second, shown block so it would not be possible to use them incorrectly since they wouldn't exist.
You guys are skipping over posts. I mistyped my code.
Topic archived. No new replies allowed.