Proposal: Add 'fillBytes' to Foreign.Marshal.Utils

Alex Petrov oleksandr.petrov at
Wed Nov 12 14:21:17 UTC 2014

Hi everyone,

Currently the memory allocated with (Foreign.Marshal.Alloc) malloc may potentially be dirty. In C this problem is usually solved by using memset.

This would be extremely useful for FFI / C interop, when a data structure is allocated within Haskell code. With memset, you can do something like

customMem <- malloc
_         <- memset (castPtr customMem) 0 #{size custom_t}
This will fill a block of allocated memory with zeroes.

For example, I've been working on FFI bindings for collectd, and when I was allocating memory, previously used within the process, it was dirty, so my CString contained a value of

"custom name7e0700490, test_plugin_LTX_module_register): symbol nd"
Instead of just

"custom name"
After using memset and filling everything with zeroes, problem never appeared again.

This can be implemented in user applications, too, although it would be really nice to have it by default.
This is a common practice in C world, and this function is not only useful for cases when the memory was just allocated from Haskell process, but also when one receives a dirty memory buffer from C code. 

The patch for proposal was implemented and is available on Phabricator:

Please share your thoughts.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Libraries mailing list