Can I use malloc?
Closed this issue · 4 comments
I am using malloc with TinyGo but with nottinygc it panics.
How can I resolve this?
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x18 pc=0x1199875]
`// These function are exported by TinyGo
malloc := mod.ExportedFunction("malloc")
free := mod.ExportedFunction("free")
// Allocate Memory
results, err := malloc.Call(ctx, nameSize)
if err != nil {
log.Panicln(err)
}
namePosition := results[0]
// This pointer is managed by TinyGo,
// but TinyGo is unaware of external usage.
// So, we have to free it when finished
defer free.Call(ctx, namePosition)
`
Can we export this
Line 53 in 59403c7
Hi @tillknuesting - at the time, the plan was for TinyGo to stop exporting those in 0.28.0 so did not export them here either. But it looks like that didn't happen yet, let me confirm if this is a long-term decision to keep the exports, and if so we'll add them.
tinygo-org/tinygo#3142 (comment)
In the meantime, you can define your own functions if needed
import "C"
//export allocate
func allocate(size uint32) unsafe.Pointer {
// IIRC, the type actually is unsigned long in wasi-libc source for some reason, or otherwise whatever C. cast works :)
return C.malloc(C.ulong(size))
}
//export deallocate
func deallocate(ptr unsafe.Pointer) {
C.free(ptr)
}
Oh, I found this even simpler workaround
tetratelabs/wazero#1429 (comment)
I think we'll probably end up exporting by default here to match 0.28 but let me hear a bit on what the plan on TinyGo is first.
@tillknuesting Thanks for bringing this up, I have made the change to export malloc/free by default. Will try to cut a release soon after debugging #13 further