Skip to content

Instantly share code, notes, and snippets.

@wholivesinapineappleunderthesea
Created March 17, 2021 18:42
Show Gist options
  • Save wholivesinapineappleunderthesea/6dac276806a55cf159ca2d50bd6fc9b2 to your computer and use it in GitHub Desktop.
Save wholivesinapineappleunderthesea/6dac276806a55cf159ca2d50bd6fc9b2 to your computer and use it in GitHub Desktop.
Allocate in a 32 bit area (Windows C/++)
static void* allocate_in_32bits(uint32_t start, uint32_t sz) {
if (!sz) return NULL;
MEMORY_BASIC_INFORMATION mbi = { 0 };
char* min = (char*)start;
char* max = (char*)UINT32_MAX - sz;
while (min < max) {
if (!VirtualQuery(min, &mbi, sizeof mbi)) return NULL;
if (mbi.State == MEM_FREE && mbi.RegionSize > sz && mbi.BaseAddress) {
void* alloc = VirtualAlloc(mbi.BaseAddress, sz, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if ((uint64_t)alloc > UINT32_MAX) { VirtualFree(alloc, 0, MEM_RELEASE); return NULL; }
if (alloc) return alloc;
}
min += sz;
}
return NULL;
}
int main(int argc, char** argv, char** envp) {
void* alloc = allocate_in_32bits(UINT16_MAX, 0x1000);
printf("@ 0x%p", alloc);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment