4

Why would one use

void *enif_alloc(size_t size) as opposed to

void *malloc(size_t size); when trying to allocate memory from an Erlang C NIF?

Reference does not specify much as to why.

http://www.erlang.org/doc/man/erl_nif.html#enif_alloc

I have seen NIF examples were malloc is used and I never see the enif_alloc. What does it do differently? Why is it better to use?

BAR
  • 15,909
  • 27
  • 97
  • 185
  • possible duplicate of [Allocating memory in Erlang C NIF](http://stackoverflow.com/questions/14420970/allocating-memory-in-erlang-c-nif) – Alok Save Jan 28 '13 at 14:03
  • 1
    Its shocking to see he is the OP of this question too. http://stackoverflow.com/questions/14420970/allocating-memory-in-erlang-c-nif – sr01853 Jan 28 '13 at 14:06
  • 3
    It's a different question, and there is little available to piece together an answer. – BAR Jan 28 '13 at 14:38
  • 4
    @Sibrajas And what's the problem with that? It is not a duplicate. And it is better to write one post per question, instead of writing one "super post" with several, possibly unrelated questions in one post. – Lundin Jan 28 '13 at 15:02

1 Answers1

13

enif_alloc uses the internal erlang memory allocators, which means that if the memory already is available in the internal VM cache it can use that memory instead of doing a system call to get the memory. This can lead to faster memory allocation in some cases, you will have to measure with your code to figure out if it makes any difference. In general I would recommend using enif_alloc.

If I remember correctly using enif_alloc also makes the memory used be included when issuing the erlang:memory command.

Lukas
  • 5,182
  • 26
  • 17
  • 1
    Perfect reason just what I was looking for. Now exactly how do you know this?? Where can I look to learn? – BAR Jan 28 '13 at 16:49
  • 2
    This particular piece of info comes from reading erts_alloc, erl_nif man pages and the corresponding source code. You also have to understand how memory allocators in general work :) – Lukas Jan 28 '13 at 22:00