Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Replacing malloc() on Windows.
#include <limits.h>
#include <malloc.h>
#include <new.h>
#include <windows.h>
#include <stddef.h>
#include <stdio.h>
namespace {
const size_t kWindowsPageSize = 4096;
const size_t kMaxWindowsAllocation = INT_MAX - kWindowsPageSize;
inline HANDLE get_heap_handle() {
return reinterpret_cast<HANDLE>(_get_heap_handle());
}
void* win_heap_malloc(size_t size) {
printf("Patatino\n");
if (size < kMaxWindowsAllocation)
return HeapAlloc(get_heap_handle(), 0, size);
return nullptr;
}
void win_heap_free(void* size) {
printf("Patatello\n");
HeapFree(get_heap_handle(), 0, size);
}
void* win_heap_realloc(void* ptr, size_t size) {
if (!ptr)
return win_heap_malloc(size);
if (!size) {
win_heap_free(ptr);
return nullptr;
}
if (size < kMaxWindowsAllocation)
return HeapReAlloc(get_heap_handle(), 0, ptr, size);
return nullptr;
}
}
extern "C" {
// Replaces malloc in ucrt\heap\malloc.cpp
__declspec(restrict) void* malloc(size_t size) {
return win_heap_malloc(size);
}
// Replaces free in ucrt\heap\free.cpp
void free(void* p) {
return win_heap_free(p);
}
// Replaces realloc in ucrt\heap\realloc.cpp
__declspec(restrict) void* realloc(void* ptr, size_t size) {
return win_heap_realloc(ptr, size);
}
// Replaces calloc in ucrt\heap\calloc.cpp
__declspec(restrict) void* calloc(size_t n, size_t elem_size) {
// Overflow check.
const size_t size = n * elem_size;
if (elem_size != 0 && size / elem_size != n)
return nullptr;
void* result = malloc(size);
if (result) {
memset(result, 0, size);
}
return result;
}
}
int main()
{
Sleep(2000);
int *patatino = (int *)malloc(16);
Sleep(2000);
free(patatino);
Sleep(2000);
return (0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.