withArray 与 newArray
在Haskell FFI中,用withArray
和newArray
分配的数组有什么本质区别?我在 c 中有一个函数可以与 newArray 一起使用,但与 withArray 一起使用会出现段错误。工作代码看起来有点像这样:
a <- newArray items
fficall a
free a
段错误的代码看起来像这样:
withArray items fficall
当 ffi 进入 blas 函数时,段错误就会发生。由于我不允许显示 c 代码,所以问题是,“请向我展示一个示例 c 函数,该函数也会在 withArray
中出现段错误,但在 newArray
中不会出现段错误”代码>."
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
."
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,newArray最终调用malloc来进行分配,而withArray调用allocaArray,这最终出现在
newAlignedPinnedByteArray#
中。也许您的函数依赖于由
malloc
分配的内存,例如尝试realloc
或free
它?From what I can see,
newArray
ends up callingmalloc
to do the allocation, whilewithArray
callsallocaArray
, which ends up innewAlignedPinnedByteArray#
.Perhaps your function is relying on the memory being allocated by
malloc
, for example by attempting torealloc
orfree
it?看起来
newArray
使用mallocArray
在堆上分配数组(需要显式释放),但withArray
分配数组使用allocaArray
在堆栈上(假设alloca
的行为方式与 C 中的行为方式相同),当调用函数返回时,它将被回收。您的列表可能太大,导致(鼓声)堆栈溢出。编辑:嗯,也许不是,看起来
allocaArray
使用 haskell 内存管理器而不是C
堆在堆中分配固定数组。It looks like
newArray
allocates the array on the heap usingmallocArray
(which will need to be free'd explicitly), butwithArray
allocates the array on the stack usingallocaArray
(assumingalloca
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 theC
heap.