1

I don't know how to ask this question as this looks very trivial, but surprisingly it's not working in my project in the visual studio. It works in the sample program. Does any optimization flag are the reason behind this?

    std::ostringstream s;
    s << "player";
    s << 1;
    cout << s.str() << endl;
    const char* pStr = s.str().c_str();
    cout << pStr<<endl;

In sample program it outputs

    player1  
    player1

but in my project const char* pStr is having "" value. Can anyone provide suggestions on what might be happening here?

Suresh Mangs
  • 705
  • 8
  • 19
novice
  • 179
  • 1
  • 5
  • 15
  • 6
    `str()` generates a `std::string` copy of the contents of `ostringstream`. As soon as the `string` goes out of scope, the `c_str()` is invalid. In your example even directly after the assignment to `pStr` – Sebastian Apr 27 '22 at 14:28
  • 2
    why do you want to keep a `const char*` in the first place? Simply store the string `std::string pStr = s.str();` and if you ever need a `const char*` you can still get it from the string – 463035818_is_not_an_ai Apr 27 '22 at 14:30
  • 1
    `pStr` is a dangling pointer. Resulting in **sad panda**. – Eljay Apr 27 '22 at 14:32
  • 4
    *"Does any optimization flags reason behind this?"* If normal optimizations look like they break your program, then it is overwhelming likely that it is because your program has a bug and the optimization just changes how that bug is expressed. It is pretty common for bugs that result in Undefined Behavior change how they affect the program when you change compiler flags. Your bug here is trying to print `pStr` which will be a dangling pointer, as explained in the comment above. – François Andrieux Apr 27 '22 at 14:34
  • 2
    Look into documentation https://en.cppreference.com/w/cpp/io/basic_ostringstream/str especially **Notes** section - it is described there that what you are doing is invalid. – Slava Apr 27 '22 at 14:34

0 Answers0