Application crashes in Debug mode, but doesn't in Release mode
Hi.
As a test, I'm using this code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
string* foo()
{
string ref = "hehhjhjhyyhjtgntgjtjumyumumuyymjijhjhjhllo";
return &ref;
}
int main()
{
string* ptr = foo();
cout << *ptr;
_getch();
return 0;
}
|
This is
very evil: i'm returning a reference to a temporary.
On GCC this program crashes (as it should)
On MSVC++ it crashes if I run it in Debug mode.
In Release mode, it just works fine.
Why?
Last edited on
Because undefined behavior is very very sneaky. Sometimes the program will appear to run properly and at other times it will crash with gusto.
Part of the reason it works sometimes could be because your string is being initialized by a constant expression.
By the way gcc also should be able to warn you about that issue.
main.cpp|9|warning: address of local variable ‘ref’ returned [-Wreturn-local-addr]| |
I'm using VC++ compiler, not GCC.
And yes, it warns me but in Debug mode it crashes, in Release mode it doesn't
Topic archived. No new replies allowed.