[Haskell-cafe] Allocating a new ByteString

Tristan Seligmann mithrandi at mithrandi.net
Tue Dec 23 16:57:46 UTC 2014


On 23 December 2014 at 08:47, Yuras Shumovich <shumovichy at gmail.com> wrote:
> On Tue, 2014-12-23 at 08:19 +0200, Tristan Seligmann wrote:
>> On 23 December 2014 at 08:10, Yuras Shumovich <shumovichy at gmail.com> wrote:
>> > Looks like you need 'unsafePackCStringFinalizer' (or one of it's variants)
>> > from Data.ByteString.Unsafe module. It lets you reuse the buffer and
>> > deallocate it in finalizer. Something similar is used e.g. in 'kyotocabinet'
>> > package.
>>
>> I tried using this, but it seems like the pointer created by
>> mallocForeignPtrBytes is freed as soon as it is no longer referenced
>> (upon returning from the function). Then, later, when the bytestring
>> is finalized, the pointer is freed again causing an abort on
>> double-free. How do I "transfer" ownership of the pointer?
>
> 'mallocForeignPtrBytes' attaches finalizer to the 'ForeignPtr', but you
> need to attach it to 'ByteString'. So you can't use
> 'mallocForeignPtrBytes', but plain old 'malloc' (from
> 'Foreign.Marshal.Alloc') should work in combination with
> 'unsafePackMallocCStringLen'. Unless I'm missing something.

Aha, that seems to work, thanks! I think I do have one minor issue
left; if an exception happens in the middle of that code, the memory
will never be free()d, but that should be solvable with an appropriate
exception handling construction, I just need to figure out exactly
what. (Actual code is here[1] if anyone is interested)

[1] https://github.com/mithrandi/ssh-key-generator/blob/master/Argh.hs#L11
-- 
mithrandi, i Ainil en-Balandor, a faer Ambar


More information about the Haskell-Cafe mailing list