In the Haskell FFI, what is the essential difference between arrays allocated with withArray
and newArray
? I have function in c that works with newArray
but segfaults with withArray
. The working code looks bit like this:
a <- newArray items
fficall a
free a
The code that segfaults looks like this:
withArray items fficall
The segfault happens up when the ffi enters a blas function. Since I'm not allowed to show the c-code, the question is, "please show me an example c-function that also segfaults with withArray
but not with newArray
."
From what I can see, newArray
ends up calling malloc
to do the allocation, while withArray
calls allocaArray
, which ends up in newAlignedPinnedByteArray#
.
Perhaps your function is relying on the memory being allocated by malloc
, for example by attempting to realloc
or free
it?
It looks like newArray
allocates the array on the heap using mallocArray
(which will need to be free'd explicitly), but withArray
allocates the array on the stack using allocaArray
(assuming alloca
behaves the way it does in C), which will be reclaimed when the calling function returns. It is possible that your list is so large that it has caused a (drum roll) Stack Overflow.
Edit: Hmm, maybe not, it looks like allocaArray
allocates a pinned array in the heap, using the haskell memory manager instead of the C
heap.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With