I have a code that returns a structure of vectors and their sizes from wasm c++ to javascript. The code I'm using is simplified below. Compiled with emscripten with :
em++ -s WASM=1 -O3 -msimd128 -s NO_EXIT_RUNTIME=1 -s ALLOW_MEMORY_GROWTH=1 testClass.c++
typedef struct Pointers_
{
int v1Size;
int16_t *v1;
int v2Size;
int8_t *v2;
int v3Size;
float *v3;
int v4Size;
unsigned int *v4;
int v5Size;
float *v5;
} Pointers;
Pointers pointers
Pointers *fillFunction(){
vector<int16_t> v1;
vector<int8_t> v2;
etc...
//do things
v1.insert(v1.end(), { some values })
v2.insert(v1.end(), { some values })
etc...
pointers.v1Size = v1.size()
pointers.v1 = v1.data()
pointers.v2Size = v2.size()
pointers.v2 = v2.data()
etc...
return &pointers
}
The problem is that when I get the values of the vectors v2 and v4 in the javascript part, the first 24 bytes are sometimes (half the calls maybe) filled with random values. But V1 and V3 are filled the exact same way and the problem never appears.
That happens because these vectors are local to the function - in its scope. As a consequence, after the function completes, the v1, v2,... instances are released. In turn each of their instance's destructors will release the allocated memory for the vector values (the one you get by calling .data()
).
WebAssembly gives you access to all memory bytes, and you are accessing the deallocated memory in JavaScript. If you are running this program "natively" (as an executable) then you may get an access violation exception, if the accessed memory is in a block that is completely released to the OS, but in WebAssembly that does not happen.