COM通信时出现间歇性内存异常错误

时间:2011-10-07 14:33:25

标签: c++ c memory-management serial-port

此代码适用于Windows 7.我试图获取对AT命令的响应并仅打印我需要的字符串部分。 Visual Studio Express随机告诉我这段代码有内存异常。它不会每次都发生。

#include <Windows.h>

#include <iostream>
#include <string>

int main()
{
    HANDLE hSerial = CreateFile("COM3",GENERIC_READ | GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);

    if(hSerial==INVALID_HANDLE_VALUE)
        std::cout << "Insert error message";

    DCB dcbSerialParams = {0};
    dcbSerialParams.DCBlength=sizeof(dcbSerialParams);

    if (!GetCommState(hSerial, &dcbSerialParams)) 
        std::cout << "Insert error message";

    dcbSerialParams.BaudRate=CBR_9600;
    dcbSerialParams.ByteSize=8;
    dcbSerialParams.StopBits=ONESTOPBIT;
    dcbSerialParams.Parity=NOPARITY;

    if (!SetCommState(hSerial,&dcbSerialParams))
        std::cout << "Insert error message";


    COMMTIMEOUTS timeouts={0};
    timeouts.ReadIntervalTimeout=50;
    timeouts.ReadTotalTimeoutConstant=50;
    timeouts.ReadTotalTimeoutMultiplier=10;
    timeouts.WriteTotalTimeoutConstant=50;
    timeouts.WriteTotalTimeoutMultiplier=10;
    if(!SetCommTimeouts(hSerial, &timeouts))
        std::cout << "Insert error message";



while(1)
{
char szBuff[50+1] = {0};
char wzBuff[14] = {"AT+CSQ\r"};

DWORD dZBytesRead = 0;
DWORD dwBytesRead = 0;


if(!WriteFile(hSerial, wzBuff, 7, &dZBytesRead, NULL))
    std::cout << "Write error";

if(!ReadFile(hSerial, szBuff, 50, &dwBytesRead, NULL))
    std::cout << "Read Error";



std:: cout << szBuff;
std::string test = std::string(szBuff).substr(8,10);
std::cout << test;
Sleep(500);
}

return 0;
}

1 个答案:

答案 0 :(得分:2)

内置的迭代器调试会抱怨你的substr()调用。你做了一些错误的假设:

  • ReadFile()只返回串口接收缓冲区中可用的内容。串口很慢,通常只能得到一个或两个字符。你不能忽视dwBytesRead。
  • 串口不返回C字符串,返回字节。你不会得到零终止符。再次使用dwBytesRead自己附加零。

继续调用ReadFile(),直到收到完整的回复。通常由换行符终止。然后处理响应。