in reply to Re^2: What difference between malloc and Newx, how attach a C string to SV directly?
in thread What difference between malloc and Newx, how attach a C string to SV directly?

Many Thanks, ikegami, just one question, how perl decide to realloc pv or just make a copy?
  • Comment on Re^3: What difference between malloc and Newx, how attach a C string to SV directly?

Replies are listed 'Best First'.
Re^4: What difference between malloc and Newx, how attach a C string to SV directly?
by ikegami (Patriarch) on Oct 01, 2019 at 15:14 UTC

    If the scalar's SvLEN is 0, the buffer exists outside of Perl's memory allocation system, so Perl must allocate a new buffer if it needs a larger buffer.

    If the scalar's copy-on-write count is larger than 1, that means two scalars are sharing the buffer, so Perl must allocate a new buffer if it needs to change the contents or size of the buffer.

    Unless I'm missing something, Perl should otherwise realloc if it needs more space, which will extend the existing buffer if possible.

    Note that Perl typically over-allocates to accommodate future growth.

    There are a couple of optimizations (copy-on-write, mortal buffer stealing) that will replace a scalar's buffer when you assign to it. But that's specifically done to avoid copying, so that's different.