Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

withArray vs newArray

Tags:

c

haskell

ffi

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."

like image 872
aleator Avatar asked Oct 17 '25 15:10

aleator


2 Answers

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?

like image 149
hammar Avatar answered Oct 20 '25 04:10

hammar


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.

like image 43
pat Avatar answered Oct 20 '25 05:10

pat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!