문제

#include <Windows.h>
#include <iostream>

using namespace std;

int main(void)
{
    unsigned char* pFoo = new unsigned char[1000];

    pFoo = (unsigned char*)VirtualAlloc(NULL, 1000, MEM_COMMIT, PAGE_EXECUTE_READWRITE);

    VirtualFree(pFoo, 0, MEM_RELEASE);

    delete[] pFoo;

    cin.ignore();
    cin.get();

    return 0;
}

This crashes for me at

delete[] pFoo;

I know this is crashing because of VirtualAlloc but I'm not sure how to fix this...

도움이 되었습니까?

해결책

You're using the same variable. So your first allocation gets leaked.

After you free it with VirtualFree, the pointer is invalid. So delete on it is undefined.

Furthermore:

You can't mix VirtualAlloc and delete for the same reason you can't mix malloc with delete.

다른 팁

unsigned char* pFoo = new unsigned char[1000];

Now pFoo holds a pointer to dynamic memory.

pFoo = (unsigned char*)VirtualAlloc(NULL, 1000, MEM_COMMIT, PAGE_EXECUTE_READWRITE);

This overwrites the old pointer, the 1000 char array is leaked.

Try:

unsigned char* pFoo = new unsigned char[1000];
unsigned char* pBar = (unsigned char*)VirtualAlloc(NULL, 1000, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
VirtualFree(pBar, 0, MEM_RELEASE);
delete[] pFoo;

Either use new/delete or VirtualAlloc/VirtualFree. You are allocating two separate memory blocks, using pFoo to refer to both (when of course it can only refer to one at a time) and then calling the two free functions with pFoo. One of those is going to fail :)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top