0

I have a simple program

const char* returnString()
{
    std::string s = "Hello";
    return s.c_str();   
}
int main()
{
const char* stemp = returnString();
return 0;
}

when my optimization flag value is /O2 stemp will have value "Hello", but when i dont have any optimization flag, stemp will be empty(which i felt is expected behavior no??). What exactly happens with /O2 that it get the value correctly? i tried seeing Disassembly, i saw the differences but i am not much knowledgeable there so i did not understood much there

novice
  • 179
  • 1
  • 5
  • 15
  • 3
    Because it's undefined behavior. `return s.c_str();` returns a dangling pointer. In this case there is no expected behavior. – Lukas-T Aug 23 '21 at 13:45
  • When `returnString` returns, `s` ceases to exist. In particular, its contents are freed. So the value returned by `s.c_str` is the address of unallocated memory, which can contain anything at all. – TonyK Aug 23 '21 at 13:50
  • yes, i agree with explanation here, but i did not understand in same Visual studio compiler, when we compile with /O2 why it holds the value?? and why it works correctly without optimization. This behavior is consistent. – novice Aug 23 '21 at 13:52
  • 3
    @novice In C++ it is important to learn to make the distinction between something being consistent, and something appearing consistent. The code contains Undefined Behavior and must therefore be considered not consistent. It may appear consistent for certain configurations of compilers, flags, and other circumstances, but it is definitely not something you can rely on. It could change at any time for any reason, including changes to apparently unrelated parts of your code, and not limited to enabling or disabling optimizations. – François Andrieux Aug 23 '21 at 13:55
  • [This](https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html) might be related – Karen Baghdasaryan Aug 23 '21 at 13:58

0 Answers0