Path: blob/main/test/browser/emmalloc_memgrowth.cpp
4150 views
#include <stdio.h>1#include <stdlib.h>2#include <emscripten/heap.h>34uint64_t nextAllocationSize = 16*1024*1024;5bool allocHasFailed = false;67void grow_memory() {8uint8_t *ptr = (uint8_t*)malloc((size_t)nextAllocationSize);9EM_ASM({}, ptr); // Pass ptr out to confuse LLVM that it is used, so it won't optimize it away in -O1 and higher.10size_t heapSize = emscripten_get_heap_size();11printf("Allocated %zu: %d. Heap size: %zu\n", (size_t)nextAllocationSize, ptr ? 1 : 0, heapSize);12if (ptr) {13if (!allocHasFailed) {14nextAllocationSize *= 2;15// Make sure we don't overflow, and also exercise malloc(-1) to gracefully return 0 in ABORTING_MALLOC=0 mode.16if (nextAllocationSize > 0xFFFFFFFFULL)17nextAllocationSize = 0xFFFFFFFFULL;18}19} else {20nextAllocationSize /= 2;21allocHasFailed = true;22}23}2425int main() {26// Exhaust all available memory.27for(int i = 0; i < 50; ++i) {28grow_memory();29}30// If we get this far without crashing on OOM, we are ok!31printf("Test finished!\n");32return 0;33}343536