[Visual Studio] Error ASSERT: "i >= 0 && i < size()", use C++ language, cooperate with Qt to develop serial communication interface

Knowledge is not alone, it must be systematic. More my personal summary and related experience can be found in this column: Visual Studio .

This bug was encountered when I was working on this project: [Visual Studio] Qt's real-time drawing curve function, using C++ language, cooperates with Qt to develop serial communication interface .

Article Directory

question

Use C++ language and cooperate with Qt to develop the serial port communication interface. When debugging dynamic drawing, it will report Debug Error!

Copy the error message so that others can retrieve my article when searching. The error message is as follows:

ASSERT: “i >= 0 && i < size()” in file
quytearray.h, line 557

The screenshot of the error is as follows:

insert image description here

solution

First locate the wrong code position and find that it is

QByteArray MyConRevBuff = m_SerialPort.read(14);

This is due to the array being out of bounds by reading more bytes than are actually available.

To get around this, a conditional statement can be used to check if there are enough bytes available for reading. If the number of available bytes is less than the requested number of bytes, you can wait for more data to arrive or do appropriate error handling. That is, changed to the following statement:

int bytesToRead = qMin(14, m_SerialPort.bytesAvailable());  // 获取可用字节数和请求字节数的较小值

if (bytesToRead >= 14) {
    
    
    QByteArray MyConRevBuff = m_SerialPort.read(14);
    // 处理读取的数据
} else {
    
    
    // 可用字节数不足,等待更多数据到达或进行错误处理
}

Such modification can ensure that the read operation is only performed when there are enough bytes available, thereby avoiding array out-of-bounds errors. If insufficient bytes are available, you can wait or error-handle as desired. hope this helps.

Ref.

Guess you like

Origin blog.csdn.net/weixin_36815313/article/details/131408365