In this case, you don't have to. When the variable that you're returning is destroyed, its memory is freed. Since you're returning an array, all the elements of the array will be destroyed by that time as well (to be more precise, their reference count is decreased when the array is deleted, only if they have no other references by that time will they be freed).
You can manually decrease the reference count of a zval by calling zval_ptr_dtor
. When its reference count reaches 0, this will free its memory as well.
Technically, an array variable is backed by a HashTable
. When the variable is destroyed, the hash table is destroyed as well. By this, the "destructor callback" associated with the HashTable
as called as well, once with each of the hash table elements as an argument. When you call array_init
, it also creates a hash table with zval_ptr_dtor
as the destructor function.
Also note that you make calls to emalloc
in two places here. The first is explicit, the other is via MAKE_STD_ZVAL
. The first one is unnecessary, but if you use it, you should call efree
before your function returns otherwise its memory leaks because it's not associated with any automatic memory management mechanism like PHP variables are.
array_init(pt[i]);
right afterMAKE_STD_ZVAL()
, forgot to add it to the example. So, if I understand correctly, I shouldn't callemalloc()
at all, becauseMAKE_STD_ZVAL()
is responsible for allocating the memory, and the memory gets deallocated when its reference count arrives at zero (and that should happen when it gets out of scope in PHP, if it's only referenced once). – Feces