Important: Please read the Qt Code of Conduct -

Help - QTcpSocket call errorString return wrong string in special case.

  • I have a issue with QTcpSocket.
    When I connectToHost with argument ("", 0) and looping with interval 500ms , action get errorString() make crash program.

    bool stop = false;
    QTcpSocket* partnerSocket = new QTcpSocket();
    class TaskPool : public QRunnable
        void run() override
            while (!stop) {
              partnerSocket -> connectToHost("", 0);
              qDebug() << this << "Socket State" << (int)partnerSocket->state();
              qDebug() << "Socket Error String : " << partnerSocket -> errorString();
    int main(int argc, char *argv[])
        QGuiApplication app(argc, argv);
        TaskPool* task = new TaskPool();
        QQmlApplicationEngine engine;
        return app.exec();

    After about 20min, errorString return some wrong string : empty or unicode string \u*** and program crashed.
    errorString() is member method of QIODevice, so i think QIODevice has the issue with memory.


    1. Void this case by using signal of QAbstractSocket to handle error and reconnect
    2. Using waitForConnected for blocking socket when you synchonize progress.

  • Lifetime Qt Champion

    Hi and welcome to the forums
    Is that code enough to reproduce it?

  • Lifetime Qt Champion

    You need a running event loop to use QTcpSocket. With your code you block the event loop. I don't think that will work.

    Also, what is the use of connecting to a host (which one?) every 500 ms. What do you think happens with the old connection in partnerSocket?

    I would not be surprised if this code has memory leaks.

  • @mrjj : oh, because i edited when type on web :D. I updated code block to confirm.

  • @aha_1980 : i think, too. But i checked source code connectToHost in case return HostNotFound, I can't see something wrong to memory leak.

  • Lifetime Qt Champion


    Since you are interested in possible failures, why not use waitForConnected ?

  • @SGaist : I think the problem can make crash in other case , so i need investigate about it.
    I changed source code using signal error() to handle error message and reconnect when state is disconnected. The program is good look.
    But i can't understand about that problem.

  • Lifetime Qt Champion

    One question is: why are you retrieving the error message right after calling connectToHost since you know that this operation may take time and the function is not blocking ?

  • @SGaist : This is bug of my friend. He unknow about not blocking socket. I investigated and fix this bug.
    I think QIODevice has bug with errorString (QIODevice is valid but errorString wrong). And I can't descript about this crash issue.
    Maybe I will investigate later.
    Thank for your help !

Log in to reply