Search code examples
c++heap-memorynew-operator

delete[] keyword after declaring array using new causing error


I have the below code snippet.

int main()
{ 
    wchar_t *wTemp = new wchar_t[ArrSize];
    std::vector<char>  SourceVector;
    std::vector<std::wstring> DestinationVector;

    for (int i = 0; i < ArrSize; i++)
    {
        SourceVector.push_back(i);
    }

    int k = 0;
    for (size_t i = 0; i < SourceVector.size(); i++)
    {
        k += swprintf(wTemp + k, ArrSize, L"%u", SourceVector[i]);      
    }

    DestinationVector.push_back(wTemp);
    delete[] wTemp;

    return 0;
}

I am declaring a char array created using the "new" keyword. Since the new keyword has been used I have used the delete[] keyword for the created array at the end.

I have a SourceVector with some data. Data in SourceVector is stored in wTemp array and the array pointer is passed to DestinationVector to store the value in array to DestinationVector.

However, sometimes

DestinationVector.push_back(wTemp);

gives an error "Unhandled exception at 0x77408509 (ntdll.dll) in ConsoleApplication1.exe: 0xC0000374: A heap has been corrupted (parameters: 0x774458A0)."

Also, the line

delete[] wTemp;

gives the same error always.

What am I doing wrong here?


Solution

  • You always write at most ArraySize characters no matter where in the array you start via wTemp + k, that will lead to buffer overrun.

    k += swprintf(wTemp + k, ArrSize-k, L"%u", SourceVector[i]); 
    

    Is the correct call, but this will only reveal the true source of the error. swprintf appends \0 (and actually writes only n-1 chars) to each string and you did not leave a place for it in the array if the vector happens to be full.

    Please do not use raw pointers, std::unique_ptr<wchar_t[]> will work just fine as is safe. But it seems to me that you can just append to std::wstring directly and then add it to the destination vector.