Reputation: 7327
I have constructed a function of type f :: Ptr Int -> IO (Int)
.
When I pass f
some pointer p
, and then try to free p
, I get a core dump.
My conclusion is that Haskell passes pointers by reference and automatically deletes them after a value is returned from a function!
Question: When f
is passed p
, does it do so by value or by reference? Does Haskell delete p
by the time the function returns?
Upvotes: 0
Views: 465
Reputation: 370435
You don't free pointers, you free memory, specifically malloc (and co.)-allocated memory. If you free a pointer to something other than malloc-allocated memory, it fails. If you free a pointer to malloc-allocated memory that has already been freed, it also fails.
When f is passed p, does it do so by value or by reference?
Usually values are in Haskell are boxed, unless you specifically use unboxed types. They're also usually lazy, so what you get is a box inside a thunk. I suppose that qualifies as passing by reference. That said, this isn't at all relevant to your problem. Pointers wouldn't behave any differently if you just passed their unboxed, strict, numeric values by value1.
Does Haskell delete p by the time the function returns?
Absolutely not. Haskell does not automatically call free
on any Ptr
s. In the absence of garbage collection2, there's no way it could even know when it's safe to call free
on a given pointer.
1 With regards to your question that is.
2 Now, of course, Haskell is garbage collected, but this doesn't apply to the values that you can have Ptr
s to.
Upvotes: 4