質問

I made a php extension which looks like:

PHP_FUNCTION(function_name)
{
    ...
    proc_data = ( char * )malloc(length);
    ...
    RETURN_STRINGL( proc_data, length, 1 );

}

function_name is the function which will be available in php code and it returns a string. But this string is allocated memory using malloc, will it be freed automatically or I've to do something about it. I'm aware of emalloc, but what difference will it make if I use it ?

Is there any better way of doing this ?

役に立ちましたか?

解決

emalloc() uses php's own memory allocator (which is optimized for php's workload, and enforces maximum memory usage).

You should use emalloc() where possible, and you must use it if PHP may free or reallocate the memory region.

The 3rd argument of RETURN_STRINGL() specifies whether it should return a copy of the string, or return the original string directly.

In the former case, PHP won't touch the original string, so you may have to free it yourself.

In the later case, PHP becomes the owner of the string. It will free the original string using efree() when the returned variable is not used / reachable anymore, so the string must have been allocated with emalloc().

If you allocate the variable yourself, you should allocate it with emalloc() and pass 0 to RETURN_STRINGL():

RETURN_STRINGL(proc_data, length, 0);

If the variable is allocated by some library and you need to free it, do this:

// RETVAL_STRINGL lets you set the return value, and then do anything before
// actually leaving the function
RETVAL_STRINGL(proc_data, length, 1);
free(proc_data);
return;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top