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