[erlang-questions] mmap file to binary

Sverker Eriksson <>
Wed Jul 14 11:47:34 CEST 2010

Max Lapshin wrote:
> I have to do so:
>     Mmap *mm;
>     mm = (Mmap *)enif_alloc_resource(mmap_resource, sizeof(Mmap));
>     mm->ptr = m;
>     mm->size = (size_t)file_stat.st_size;
>     m_bin = enif_make_resource_binary(env, mm, mm->ptr, mm->size);
>     enif_release_resource(mm);   % <---------
>     return enif_make_tuple2(env, enif_make_atom(env, "ok"), m_bin);
> If I don't add enif_release_resource, it will never be garbage
> collected. Why I have to do so
That was a design choice. Ownership of resources are never transfered.

enif_allloc_resource gives you ("the NIF") ownership of the resource.
enif_make_resource and enif_make_resource_binary adds a new ownership 
from the created Erlang term.

So, to really free a resource, both "the NIF" ownership has to be 
released by calling enif_release_resource and all referring terms has to 
be garbage collected.

/Sverker, Erlang/OTP

More information about the erlang-questions mailing list