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

kar*_*med 1 c++ memory mbed

如果您有兴趣,可以了解一些背景知识...

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

守则和问题

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

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

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

现在,我发现只需重新排序cout命令,“ stuffed 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;
}
Run Code Online (Sandbox Code Playgroud)

tem*_*def 6

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

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

第一行不向字符数组写入任何内容。而是,它创建一个char数值为1 的变量。请注意,short这里不需要强制转换,也没有任何作用-您是要写其他东西吗?

第二行不创建指向数组的指针。而是,它创建一个指向data变量的指针。您可能会认为这是指向长度为1的数组的指针,但这可能不是您的意图。

上面的两行本身并没有做任何坏事。但是,下一行是一个实际的问题:

unsigned short result = pec15(dataPtr);                    //Pass data pointer to pec calculator
Run Code Online (Sandbox Code Playgroud)

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

我不确定如何解决此问题,因为我不太了解您的代码背后的意图。您的意思是制作一个16个元素的数组吗?您是要创建一个填充有值的数组0x1吗?正确的解决方法取决于该问题的答案。