What is the best way to reallocate memory for char array?

For example I’ve allocated memory for char *str:

str = ngx_pnalloc(r->pool, len1);

Then I’ve added some data to “str”:

ngx_sprintf(str, “abc”);

How should I reallocate this memory? Should I use:

str = ngx_pnalloc(r->pool, len2);

? And I would like to keep the str’s “abc” data as well.

Posted at Nginx Forum:

P.S. len2 > len1

Posted at Nginx Forum:

Hello!

On Mon, Nov 17, 2014 at 09:09:34AM -0500, kay wrote:

str = ngx_pnalloc(r->pool, len2);

? And I would like to keep the str’s “abc” data as well.

Best strategy is to allocate len1 + len2 from the start. E.g.,
you may try looking into autoindex module: it calculates size of a
buffer it will need, and then allocates the buffer.


Maxim D.
http://nginx.org/

Thanks.

Is it necessary to use ngx_pfree(str) at the end of my function?

Maxim D. Wrote:

ngx_sprintf(str, “abc”);


Maxim D.
http://nginx.org/


nginx mailing list
[email protected]
nginx Info Page

Posted at Nginx Forum:

Hello!

On Mon, Nov 17, 2014 at 09:35:18AM -0500, kay wrote:

Thanks.

Is it necessary to use ngx_pfree(str) at the end of my function?

As long as you allocate memory from a pool, it’s not required to
free the memory explicitly via ngx_pfree(). Memory will be
freed automatically on the pool destruction. Moreover, in most
cases ngx_pfree() will not be able to do anything as it can only
free large blocks of memory.

The ngx_pfree() function is only useable in some special cases
when you have to free large blocks of memory before the pool will
be destroyed. For example, nginx uses ngx_pfree() to free
connection’s buffer memory for idle keepalive connections, see
ngx_http_set_keepalive().


Maxim D.
http://nginx.org/