std::bad_alloc error while appending to QString



  • Hi everyone and thanks for your care to this question.

    I`m writing a class, that gets a base URL, and 2 QStringLists of parametr values and names, then appends them to the base url to make a working URL, send request and get reply.

    The problem is, the program crashes whie appending to the finalURL. see this code:

    void NetworkObject::makeURL()
    {
        _finalURL.append(_baseURL);
        _finalURL.append("?");
        qDebug() << _finalURL.toLatin1();
        for (int i = 0; i < _varNameList.size(); i++)
        {
            _finalURL.append(_varNameList[i]);
            _finalURL.append("=");
            _finalURL.append(_varValueList[i]); //##
            if (i =! _varNameList.size() - 1)
            {
                _finalURL.append("&");
            }
        }
    }
    

    Using debugger, I found it occurs on the line marked with ##.

    Something makes me amazed and that is, I made a mistake before, and instead of that if statement, just wrote:

    _finalURL.append("&");
    

    and it had no error in this scope.



  • @Ali-Rashidi
    I would have

    _finalURL = _baseURL;
    

    as the first line. That way you're sure that you know _finalURL is not filled with results from previous calls. std::bad_alloc would suggest that you're running out of memory. These days that's pretty hard to do.

    As an aside, did you consider using QStringList::join?

    Mike


  • Qt Champions 2016

    Hi

    The if looks wrong to me

    if (i =! _varNameList.size() - 1)

    I would expect

    if ( i ! = _varNameList.size() - 1)

    Also as Mike says, it sounds like out of memory but URLs are normally not that big.
    Have you tried qDebug() << varNameList[i]; to see what u are appending?
    (in the loop)



  • @mrjj Oh I forgot that, however, I still faced SEGFAULT using this approach in another part, so changed the method completely, thanks for help


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.