How to free erlang term

In the erlang port program example

tuplep = erl_decode(buf); fnp = erl_element(1, tuplep); argp = erl_element(2, tuplep); ... erl_free_compound(tuplep); erl_free_term(fnp); erl_free_term(argp); 

Both erl_free_compound and erl_free_term are used to free the term (and its subsegment) separately from the same ETERM *. From the documentation of erl_free_compund (), it says

erl_free_compound () will recursively free all sub-members associated with the given member of Erlang

So my question is whether erl_element () makes a copy of the element, which, if it is not freed separately, will lead to a memory leak, and the situation above can lead to double free access, which is detected and processed by erl_free_term.

+4
source share
1 answer

The erl_interface library really uses a kind of reference counting system to track distributed ETERM structures. Therefore, if you write:

 ETERM *t_arr[2]; ETERM *t1; t_arr[0] = erl_mk_atom("hello"); t_arr[1] = erl_mk_atom("world"); t1 = erl_mk_tuple(&t_arr[0],2); 

You have created three (3) Erlang members (ETERM). Now, if you call: erl_free_term (t1), you only free the tuple, not the other two ETERMs. To free all allocated memory, you would have to call:

 erl_free_term(t_arr[0]); erl_free_term(t_arr[1]); erl_free_term(t1) 

To avoid all these calls in erl_free_term (), you can use: erl_free_compund (). He is "deeply" free from all ETERM. Thus, the above can be accomplished using:

 erl_free_compund(t1) 

Thus, this procedure allows you to write in a more compact form, where you do not need to remember links to all ETERM subcomponents. Example:

 ETERM *list; list = erl_cons(erl_mk_int(36), erl_cons(erl_mk_atom("tobbe"), erl_mk_empty_list())); ... /* do some work */ erl_free_compound(list); 

Refresh . To check if you really exempt all creation conditions, you can use this code snippet ( original entry manually :

 long allocated, freed; erl_eterm_statistics(&allocated,&freed); printf("currently allocated blocks: %ld\n",allocated); printf("length of freelist: %ld\n",freed); /* really free the freelist */ erl_eterm_release(); 

( answer accepted here )

+3
source

Source: https://habr.com/ru/post/1487379/


All Articles