修复bug后的代码如下:

void Decoder::checkFrame(const char *msg, lidar::LidarMsg& lidarMsg) {
    std::cout << "checking frame" << std::endl;
    std::cout << "stream len: " << strlen(msg) << std::endl;
    
    const char* head = msg;
    const char* tail = msg + strlen(msg) - 2;
    
    // TODO: 校验和
    if (strncmp(head, "aa", 2) != 0 || strncmp(tail, "16", 2) != 0) {
        std::cout << "the frame broken" << std::endl;
        lidarMsg.isBroken = true;
    }
}

修复的内容包括:

  1. 修正了头部和尾部字符串比较的错误。原先的代码使用了!=进行比较,但是字符串比较应该使用strncmp函数进行比较。
  2. 修正了strncpy函数的使用。原先的代码在使用strncpy函数时没有为head分配内存,导致可能出现未定义的行为。修复后的代码直接将msg赋值给head指针。
  3. 修正了tail指针的计算。原先的代码计算tail指针时没有考虑到尾部两个字符,修复后的代码将tail指针计算为msg + strlen(msg) - 2
void DecodercheckFrameconst char msg lidarLidarMsg& lidarMsg stdcoutchecking framestdendl; stdcoutstream len strlenmsgstdendl; const char head; strncpyhead msg

原文地址: https://www.cveoy.top/t/topic/irD1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录