emscripten-core / emscripten-core/emscripten

C function free not working. Memory leak of malloc and free.

Open
#12,776 7 comments 0 reactions 0 assignees View on GitHub
wontfix
Dominant language
C++
Stars
27.6k
Forks
3.6k
Avg merge
1d 1h
Merged PRs (30d)
105

Description

first thing first, I am apperacited to get anyone's help.

I compile and run a simple demo in chrome. But I find the demo exist memory leak, and I am confussing about it.

Environment infomation:
1. chrome 86.0.4240.193(stable 64bit) / firefox 82.0.3(64bit)
2. Windows 10 64bits WSL2 `Linux DESKTOP-WINDOWS 4.4.0-18362-Microsoft #1049-Microsoft Thu Aug 14 12:01:00 PST 2020 x86_64 x86_64 x86_64 GNU/Linux`
3. emsdk 2.0.8

My demo consist of:
1. test_memory_recycle.html

```html

Test memory recycle



test_memory_recycle, please open console





var api = '';
var Module = {};
Module.onRuntimeInitialized = _ => {
api = {
entry: Module.cwrap('test_entry', 'number', []),
};
};

function OnClickTest() {
api.entry();
window.alert('Please open devtool panel');
}

```

2. test_memory_recycle.c

```c

#include
#include
#include
#include
#include
#include
#include

#define BLOCKLEN (2048)
static long num = 0;

void main_loop()
{
char* buf = (char*)malloc(BLOCKLEN * sizeof(char));
sprintf(buf, "You are in %s function, test memory malloc and free, test count: %ld", __FUNCTION__, ++num);
printf("%s\n", buf);
free(buf);
buf = NULL;

if (num == LONG_MAX)
{
emscripten_cancel_main_loop();
}
}

int test_entry()
{
emscripten_set_main_loop(main_loop, 60, 0);
return 0;
}
```

3. compile command
```sh
prog=test_memory_recycle

echo make_${prog}
emcc ${prog}.c -v -s WASM \
-O4 -g4 \
-s EXPORTED_FUNCTIONS="['_test_entry','_malloc','_free']" \
-s EXTRA_EXPORTED_RUNTIME_METHODS="['cwrap']" \
-fsanitize=address \
-s PROXY_TO_PTHREAD=1 -s USE_PTHREADS -s PTHREAD_POOL_SIZE=8 \
-s INITIAL_MEMORY=67108864 -s ALLOW_MEMORY_GROWTH=1 \
-s MAXIMUM_MEMORY=134217728 -s ASSERTIONS=1 \
-o ${prog}.js
```

Eventually, the webpage break down and the console end with:
```
You are in main_loop2 function, test memory malloc and free, test count: 13838

Cannot enlarge memory, asked to go up to 134696960 bytes, but the limit is 134217728 bytes!
==42==ERROR: AddressSanitizer: allocator is out of memory trying to allocate 0x800 bytes
==42==FATAL: AddressSanitizer: internal allocator is out of memory trying to allocate 0xf bytes
program exited (with status: 1), but EXIT_RUNTIME is not set, so halting execution but not exiting the runtime or preventing further async execution (build with EXIT_RUNTIME=1, if you want a true shutdown)
```

Is there something I missed?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.