How to fix heap damage

I tried to create a very minimal memory reader library to read it unsigned int. However, I run the "HEAP CORRUPTION DETECTED" error message when the method ReadUnsignedIntwants to return.

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

As I read, this may be the reason when trying to double delete something. This may be caused by misuse std::tr1::shared_ptr, but I cannot determine what I am doing wrong with them. The code is as follows (processing error 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;
}
+3
source share
4 answers

, .

shared_ptr delete , .

, , new - not new[].

shared_ptr<vector<byte> > boost::shared_array<byte>.

+4

:

new byte(numberOfBytes)

numberOfBytes.

:

new byte[numberOfBytes]    

numberOfBytes long.

, 4 , ? unsigned int .

+2

. , , shared_ptr. , , , - :

unsigned Memory::ReadUnsignedInt(unsigned address) { 
    unsigned ret;
    ReadProcessMemory(m_hProcess.get(), (void *)address, &ret, sizeof(ret), NULL);
    return ret;
}

std::vector<char> Memory::ReadBytes(unsigned address, int num) { 
    std::vector<char> ret(num);
    ReadProcessMemory(m_hProcess.get(), (void *)address, &ret[0], num, NULL);
    return ret;
}

ReadUnsignedInt :

template <class T>
T Memory::Read(unsigned address) { 
    T ret;
    ReadProcessMemory(m_hProcess.get(), (void*)address, &ret, sizeof(ret), NULL);
    return ret;
}

, , :

int x = Read<int>(wherever);
char a = Read<char>(wherever);

:

template <class T>
Memory::Read(unsigned address, T &t) { 
    ReadProcessMemory(my_hProcess.get(), (void *)address, &t, sizeof(t), NULL);
};

, :

Read(wherever, some_int);
Read(somewhere, some_long);

..

char, , , - V++ ( ) , " ", , , , ReadBytes , , . , , , ReadBytes , "" "" .

, - --, , . , , .

+2

, new byte(numberOfBytes) new byte[numberOfBytes]. . , @ephemient, shared_ptr , delete, delete[]. , undefined.

0

Source: https://habr.com/ru/post/1720097/


All Articles