I want to know how to properly delete the memory of std::vector allocated in c++ code and passed to js as function return.
My c++ code is
#include <vector>
#include <emscripten/bind.h>
using namespace emscripten;
std::vector<int> intArrayToVector(uintptr_t input, int num){
std::vector<int> vec;
const int* ptr = reinterpret_cast<int*>(input);
for(int i=0; i<num; i++){
int val = *(ptr+i);
vec.push_back(val);
}
return vec;
}
EMSCRIPTEN_BINDINGS(test){
register_vector<int>("VectorInt");
function("intArrayToVector", &intArrayToVector, allow_raw_pointer<arg<0>>());
}
My html code is
<html>
<body>
<script src="test.js"></script>
<script>
var num = 6;
var buf = Module._malloc(100);
var arr = new Int8Array(num);
for(var i=0; i<num; i++){
arr[i] = i+2;
}
Module.HEAP8.set(arr, buf);
var v = Module.intArrayToVector(buf, num);
for(var i=0; i<num; i++){
console.log(v.get(i));
}
Module._free(buf);
v.resize(0, 0);
v.delete();
v = {};
</script>
</body>
</html>
I tried the following code to delete the allocated memory but nothing is happening.
v.resize(0, 0);
v.delete();
v = {};
I think v.delete()
works.
for (var j = 0;; j++) {
var v = Module.intArrayToVector(buf, num);
for(var i=0; i<num; i++){
console.log(v.get(i));
}
}
Above infinite loop aborts by Cannot enlarge memory arrays.
But with v.delete()
at end of loop, this program doesn't stop.