Skip to content

Instantly share code, notes, and snippets.

@mmozeiko

mmozeiko/new_delete.cpp

Last active Jul 20, 2020
Embed
What would you like to do?
Example for overriding global new/delete
// compile as console app:
// cl -O2 -Zi -Gm- -GR- -EHa- -GS- -Gs999999 a.cpp /link /subsystem:console -nodefaultlib -stack:0x100000,0x100000 kernel32.lib
#include <stddef.h>
#include <windows.h>
void* operator new(size_t size)
{
return HeapAlloc(GetProcessHeap(), 0, size);
}
void operator delete (void* ptr, size_t size)
{
HeapFree(GetProcessHeap(), 0, ptr);
}
struct C { int x; };
class BigClass
{
public:
BigClass(int arg1, const char* string)
{
const char msg[] = "BigClass constructor\n";
DWORD written;
WriteConsoleA(GetStdHandle(STD_OUTPUT_HANDLE), msg, sizeof(msg), &written, NULL);
}
~BigClass()
{
const char msg[] = "BigClass destructor\n";
DWORD written;
WriteConsoleA(GetStdHandle(STD_OUTPUT_HANDLE), msg, sizeof(msg), &written, NULL);
}
};
void __stdcall mainCRTStartup()
{
C* c = new C;
c->x = 100;
delete c;
BigClass* big = new BigClass(1, "lol");
delete big;
ExitProcess(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment