Search code examples
c++shared-ptrraii

How to fix heap corruption


I've tried to build a very minimalistic memory read library to read some unsigned ints out of it. However, I run into a "HEAP CORRUPTION DETECTED" error message when the ReadUnsignedInt method wants to return.

HEAP CORRUPTION DETECTED. CRT detected that the application wrote to memory after end of buffer.

As I have read, this may be the cause when trying to double delete something. This may be caused by some incorrect usage of the std::tr1::shared_ptr but I cannot determine what I am doing wrong with them. Code is as follows (error handling omitted):

unsigned int Memory::ReadUnsignedInt (unsigned int address) const {
    std::tr1::shared_ptr<byte> bytes = 
        this->ReadBytes(address, sizeof(unsigned int));
    return *((int*)bytes.get());
    // correct value (how to improve this ugly piece of code?)
}

std::tr1::shared_ptr<byte> Memory::ReadBytes (
    unsigned int address, int numberOfBytes) const
{
    std::tr1::shared_ptr<byte> pBuffer(new byte(numberOfBytes));
    ReadProcessMemory(m_hProcess.get(), (LPCVOID)address, 
        pBuffer.get(), numberOfBytes * sizeof(byte), NULL))
    return pBuffer;
}

Solution

  • Michael and Naveen have both found the same major flaw in your code, but not the only flaw.

    shared_ptr will delete the pointed-at object when its reference count goes to zero.

    This means you can only give it objects allocated by new -- not new[].

    You may wish to use shared_ptr<vector<byte> > or boost::shared_array<byte> instead.