Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Strange behavior of .toStdString()



  • Hi all,

    I just came across the following subtlety: The code

    QString a("121");

    std::string s = a.toStdString();
    const char* p = s.c_str();
    const char* q = a.toStdString().c_str();

    for (int i = 0; i < 4; i++) std::cout << (int)p[i] << " "; std::cout << std::endl;
    for (int i = 0; i < 4; i++) std::cout << (int)q[i] << " "; std::cout << std::endl;

    results in

    49 50 49 0
    0 50 49 0

    Why does the first byte differs depending on using .toStdString() and .c_str() in one resp. two different lines?

    Thanks a lot in advance!



  • because accessing q is undefined behaviour.
    a.toStdString() returns a temporary (std::string) object, you take its address and then the object gets deleted.

    It's equivalent to:

    const char* q;
    {
    std::string p = a.toStdString();
    q = p.c_str();
    }


  • Got it! Thanks a lot!


Log in to reply