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

问题描述 投票:1回答:1

对于嵌入式系统,我正在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触发了断点”。我认为问题出在为动态字节数组创建和/或释放内存。

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

提前感谢。

亲切的问候,弗兰克

c crc modbus crc16
1个回答
0
投票

问题是,当仅分配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值将为非零。

© www.soinside.com 2019 - 2024. All rights reserved.