验证动态字节数组的 CRC 时崩溃 | C

标签 c crc modbus crc16

对于嵌入式系统,我正在用 c 语言编写代码,以根据提供的 CRC 验证接收到的字节数组。系统在 RTU Modbus 中处于事件状态。

在我的单元测试中,我有以下(正确的)字节数组:

unsigned char frame[7] = { 0x01, 0x04, 0x02, 0x03, 0xFF, 0x80, 0xF9 }

最后两个字节是我要验证的提供的 CRC 代码。

我的做法是将接收到的数组拆分为两个数组。第一个数组的长度为 n-2,第二个数组的长度为 2。然后根据第一个数组创建自己的CRC码,最后想验证第二个数组和自己的CRC码是否相同。

这是我现在的代码:

bool validateCrc16ModbusFrame(unsigned char frame[])
{
   // A valid response frame consists of at least 6 bytes.
   size_t size = sizeof frame;  
   if (size < 6) {
       return false;
   }

   // Split the frame into the 'bytes to check' and the 'provided CRC.'
   int newSize = size - 2;
   unsigned char* bytesToCheck = (unsigned char*)_malloca(newSize + 1); // Not sure about this line.
   char providedCrc[2];
   memcpy(bytesToCheck, frame, newSize * sizeof(int));
   memcpy(providedCrc, &frame[newSize], 2 * sizeof(int));

   // Calculate the CRC with the bytes to check.
   uint16_t calculatedCrc = calculateCrc16Modbus(bytesToCheck, newSize); // This function calculates the correct CRC code.
   _freea(bytesToCheck); // Not sure about this line.

   // The CRC is provided as two uint8_t bytes. Convered the two uint8_t to one uint16_t.
   uint8_t firstByteProvidedCrc = providedCrc[0];
   uint8_t secondByteProvidedCrc = providedCrc[1];
   uint16_t uint16ProvidedCrc = ((uint16_t)firstByteProvidedCrc << 8) | secondByteProvidedCrc;

   // Compare the provided CRC and the calculated CRC.
   bool result = uint16ProvidedCrc == calculatedCrc;
   return result;
}

但是当我运行测试代码时它崩溃并显示消息'!!这个测试可能已经崩溃了!!'当我调试测试代码时,出现异常消息“TestProjectName.exe 已触发断点”。我认为问题出在为动态字节数组创建和/或释放内存。

有人知道我做错了什么吗?

提前致谢。

亲切的问候,弗兰克

最佳答案

问题是当只分配 newsize+1 个字符时,memcpy 调用将 newsize 乘以 sizeof(int)。它们可能应该是:

   memcpy(bytesToCheck, frame, newSize);       /* no sizeof(int) */
   memcpy(providedCrc, &frame[newSize], 2);    /* no sizeof(int) */

此外,您不需要复制或拆分数组。您可以计算原始数组的 CRC,包括附加的 CRC,如果 CRC 未后补,则生成的 CRC 将为零,如果 CRC 为后补,则生成的 CRC 将为某个非零常数值。

关于验证动态字节数组的 CRC 时崩溃 | C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58509485/

相关文章:

c - 高效划分大功能

c - 双缓冲设计I/O同步

c - 如何打印格式化字符?

c - 在 VSCode 中使用 gcc 编译 C 程序时出错

c# - 如何计算 C#.net 中文件的 CRC 值?

c++ - 查找使用了哪个校验和

python - Python 中的 ModbusTCP 服务器/从站实现 (pymodbus)

mysql - 每1秒从PLC收集数据-希望在数据变化时获取数据

c - modbus 十六进制地址转换