C++:为什么这段代码给我内存问题/未定义的行为?

C++: Why is this code giving me memory issues / undefined behavior?

本文关键字:问题 内存 未定义 为什么 段代码 代码 C++      更新时间:2023-10-16

如果你有兴趣的话,可以介绍一下背景...

下一段代码是尝试使用循环冗余校验 (CRC-15) 实现数据包错误代码生成器。这用于检测通信数据损坏。不需要更详细的介绍。

代码和问题

init_PEC15_Table函数是一个查找表生成器。

PEC15函数接受数据输入,计算解决方案的地址并在查找表中查找结果。

data 是一个字符数组,我为其分配了值 1。这将传递给 pec15。

现在,我发现通过对 cout 命令重新排序,我感兴趣的输出"填充 pec"的值会发生变化。通过在线阅读,我了解到这可能是由于内存堆栈意外更改,从而影响结果寄存器,这可能是由于对其他变量的越界操作。我的理解有误吗?

现在,我是一个初学者,这是非常令人生畏的。我可能犯了一些我不知道的严重错误,所以请随时将代码撕成碎片。 此外,如果重要,此代码在 mbed LPC1768上运行。

#include <iostream>

using namespace std;
unsigned short pec15Table[256];
const unsigned int CRC15_POLY = 0x4599;

void init_PEC15_Table() // Cyclical Redundancy Check lookup table generator function
{
unsigned short rem;
for (int i = 0; i < 256; i++)
{
rem = i << 7;
for (int bit = 8; bit > 0; --bit)
{
if (rem & 0x4000)
{
rem = ((rem << 1));
rem = (rem ^ CRC15_POLY);
}
else
{
rem = ((rem << 1));
}
}
pec15Table[i] = rem & 0xFFFF;
//        cout << hex << pec15Table [i] << endl;
}
}
unsigned short pec15(char* data, int lengt = 16)  //Takes data as an input,
{
int rem, address;
rem = 16;//PEC seed (intial PEC value)
for (int i = 0; i < lengt; i++)
{
address = ((rem >> 7) ^ data[i]) & 0xff;//calculate PEC table address
rem = (rem << 8) ^ pec15Table[address];
}
return (rem * 2);//The CRC15 has a 0 in the LSB so the final value must be multiplied by 2
}
int main()
{
init_PEC15_Table();         //initialise pec table
char data = (short) 0x1 ;   // Write 0x1 to char array containing the data 0x1
char* dataPtr = &data;      // Create a pointer to that array
unsigned short result = pec15(dataPtr);                    //Pass data pointer to pec calculator

cout << "data in: " << (short) *dataPtr << endl;        //Print the short representation of the char data array (Outputs 1)
cout << "size of data: " << sizeof(*dataPtr) << endl;   //Print the size of the char array (Outputs 1)
cout << "stuffed pec: " << result << endl;                 //Print the output of the pec calculation    
return 0;
}

您在此处编写的代码与您编写的注释不同步:

char data = (short) 0x1 ;   // Write 0x1 to char array containing the data 0x1
char* dataPtr = &data;      // Create a pointer to that array

第一行不会向字符数组写入任何内容。相反,它会创建一个数值为 1 的char变量。请注意,这里不需要short演员阵容,也没有效果——你的意思是写别的东西吗?

第二行不创建指向数组的指针。相反,它会创建一个指向data变量的指针。您可能会将其视为指向长度为 1 的数组的指针,但这可能不是您的本意。

上面的两行本身并没有做任何坏事。然而,下一行是一个真正的问题:

unsigned short result = pec15(dataPtr);                    //Pass data pointer to pec calculator

请记住,pec15有第二个参数,应该表示传入数据的长度。由于您未指定它,因此它默认为 16。但是,dataPtr指针仅指向单个char值,而不是 16 个char值,因此这会导致未定义的行为。

我不确定如何解决这个问题,因为我对您的代码背后的意图没有很好的了解。你的意思是制作一个十六元素的数组吗?你的意思是创建一个填充值0x1的数组吗?此处的正确修复取决于该问题的答案。

尝试:

unsigned short result = pec15(dataPtr, 1);

否则lengt为 16(具有默认值)。我还建议删除默认值lengt,因为它在函数pec15上下文中几乎没有意义。