Created
June 23, 2016 21:00
-
-
Save dcci/f83538d46dbcde9457bc663a2218c97e to your computer and use it in GitHub Desktop.
Replacing malloc() on Windows.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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