0

The problem with the following is that the function returns a pointer to a temporary. However it builds and runs fine here, Qt Creator on macOS.

const char* get_str()
{
    QByteArray arr("Some text");
    return arr.constData();
}

int main()
{
    const char *s = get_str();
    printf("%s\n", s);
    return 0;
}

How can I make it fail? Or is this one of those undefined behavior cases?

I think by doing printf("%s\n", get_str()); we escape the problem, right?

KcFnMi
  • 5,516
  • 10
  • 62
  • 136
  • 2
    [Undefined Behaviour](https://en.cppreference.com/w/cpp/language/ub) is Undefined. One of the possible behaviours is appearing to work .... until it does not, usually during a demo to a customer. – Richard Critten Dec 27 '22 at 16:55
  • 1
    TL;DR version: You cannot reliably make it fail. – user4581301 Dec 27 '22 at 16:59
  • What about the last question, am I really escaping the problem by accessing it on the same line? Or am I still on undefined behavior territory? – KcFnMi Dec 28 '22 at 02:02
  • Still UB. `arr` is destroyed when `get_str` exits, and that's before `printf` gets its look at the returned pointer. – user4581301 Dec 28 '22 at 06:55
  • Your `get_str` function is guaranteed to return a dangling pointer no matter how it is called. – JaMiT Dec 28 '22 at 07:43

0 Answers0