简体   繁体   中英

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:

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). Then delete it with delete[] . You could also use stack allocation, or std::vector<byte> since this is c++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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