Search code examples
c++arrayspointersarduinodelete-operator

delete original array pointer after copy sets first 3 bytes to 0


The following program works untill a buffersize of something like 135. If the buffer gets any larger, the first 3.5 bytes get printed out as 0. (on a MKR1000 arduino)

uint8_t* bufferOut;
size_t sizeOut;

void SendMessage()
{
    fillBuffer();
    sendBuffer();
}

void fillBuffer()
{
    sizeOut = 12; //just an example
    uint8_t* tempBuffer2 = new uint8_t[sizeOut];
    bufferOut = tempBuffer2;
    delete[] tempBuffer2;
}

void sendBuffer()
{
    Serial.Write(bufferOut, sizeOut);
}

What am I doing wrong? Would std::vector be more suitable here?

Thanks!


Solution

  • bufferOut = tempBuffer2;
    delete[] tempBuffer2;
    

    After these operations, bufferOut is an invalid pointer because the object that it used to point to was destroyed. That in itself doesn't cause any undefined behaviour, but presumably you've simply failed to create a mcve, and the problem is actually caused by you later using the invalid pointer.

    Would std::vector be more suitable here?

    Most likely, yes.