#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