简体   繁体   English

数组分配访问冲突

[英]array assignment access violation

I've read many Q&A's which seemed similar to this problem but haven't found any answers yet: I have to make some assignments to a dynamic byte array in the fillbyte function like this: 我已经阅读了许多类似于此问题的问答,但尚未找到任何答案:我必须在fillbyte函数中对动态字节数组进行一些分配,如下所示:

int Error;
result = fillbyte (&Error);

if I comment the line shown below, everything works fine. 如果我评论下面显示的行,则一切正常。 but if that line gets executed, the second time that this function is called, access violation exception will be raised however the first time the code runs properly and everything goes alright. 但是,如果执行了该行,则第二次调用此函数,但是将在第一次代码正常运行且一切正常时引发访问冲突异常。 I can't seem to find the problem with this line of code or another way to fill the array with password bytes. 我似乎找不到这行代码或用密码字节填充数组的另一种方法的问题。

Bool fillbyte(int *Error)
{
    byte BCC;
    byte *Packet1 = new byte;
    *Packet1 = 0x01;
    *(Packet1+1) = 'P';
    *(Packet1+2) = '1';
    *(Packet1+3) = STX;
    *(Packet1+4) = '(';
    int add = sizeof(readingprops.password)*2;
    for(int i=0;i<add;i++)
    {
        *(Packet1+(5+i)) = readingprops.password[i];     //this line raises the problem
    }
    *(Packet1+add+5) = ')';
    *(Packet1+add+6) = ETX;
    BCC = calc.CalcBCC(Packet1,add+7);
    *(Packet1+add+7) = BCC;
    SerialPort.Write(Packet1,add+8);
    delete Packet1;
    return true;
}

Any help would be appreciated 任何帮助,将不胜感激

I don't see how it can ever work. 我不知道它怎么能工作。 You allocate one byte on the heap but treat it as multiple bytes: 您在堆上分配一个字节,但将其视为多个字节:

byte *Packet1 = new byte;
*Packet1 = 0x01;
*(Packet1+1) = 'P';  // !!!
*(Packet1+2) = '1';  // !!!
*(Packet1+3) = STX;  // !!!
*(Packet1+4) = '(';  // !!!

Here you allocate just one byte 在这里您只分配一个字节

byte *Packet1 = new byte;

and then use the pointer beyond the allocated memory 然后使用指针超出分配的内存

*(Packet1+1) = 'P';
*(Packet1+2) = '1';
*(Packet1+3) = STX;
*(Packet1+4) = '(';

This causes undefined behaviour, sometimes it may work. 这会导致不确定的行为,有时可能会起作用。 So you want something like 所以你想要像

byte Packet1 = new byte[size]

where size is appropriate for your needs (probably add + 8 , since this is the amount of bytes you write to in that function). 大小适合您的需要(可能add + 8 ,因为这是您在该函数中写入的字节数)。 Then delete it with delete[] . 然后使用delete[]删除它。 You could also use stack allocation, or std::vector<byte> since this is c++. 您也可以使用堆栈分配或std::vector<byte>因为这是c ++。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM