Search code examples
c++qtmemory-leaksqt5qpixmap

QPixmap causes memory leak?


I stream MJPEG from server and update QLabel's QPixmap every time a valid frame received. Memory usage swells in time and I cannot figure out why. Is this a wrong use of QPixmap?

    case StreamState::Streaming: {
        int ind_start_bytes = m_buffer.indexOf("\xff\xd8");
        int ind_end_bytes = m_buffer.indexOf("\xff\xd9");
        if(ind_start_bytes != -1 && ind_end_bytes != -1) {
            if(ind_start_bytes < ind_end_bytes){
                QByteArray image_data = m_buffer.mid(ind_start_bytes, ind_end_bytes + 2);
                m_buffer = m_buffer.mid(ind_end_bytes+2);
                QPixmap pmap;
                if(pmap.loadFromData(image_data, "JPEG")) {
                    setPixmap(pmap.scaled(pmap.size(), Qt::KeepAspectRatio));
                }
            }
        }
    }

Here's the github link for full code. mjpegstreamer.cpp for related code.


Solution

  • It is the m_buffer that is swelling. The code i posted consumes frames with fifo logic. So I replaced

    int ind_start_bytes = m_buffer.indexOf("\xff\xd8");
    int ind_end_bytes = m_buffer.indexOf("\xff\xd9");
    

    with

    int ind_start_bytes = m_buffer.lastIndexOf("\xff\xd8");
    int ind_end_bytes = m_buffer.lastIndexOf("\xff\xd9");
    

    If by any chance more than one frames exist in the m_buffer, we will be consuming the last one and remove the ones on the left. Problem seems to be solved now. This apparently has nothing to do with QPixmap.