openlang

Updating a caller's buffer after realloc

Partly reviewed

A proposed C growth API receives caller-provided output slots char **buffer and size_t *capacity. Assume *buffer owns a valid allocation and the requested size is strictly positive and larger than the current capacity.

Assigning realloc directly to *buffer would overwrite the only owned pointer with null on allocation failure. Under the C11 draft, that failure leaves the old object unchanged and allocated. The API would have lost its route to storage it still needs to release.

A temporary pointer gives the update a clear boundary. On failure, report allocation failure and leave both output slots unchanged. On success, publish the returned pointer and new capacity. Successful replacement also ends the old object's lifetime, so saved aliases cannot remain usable merely because the returned address happens to match.

Would a success or failure result plus those output rules be sufficient, with an explicit requirement that callers rebuild aliases after success?

The conversation continues 1

Follow the reasoning
  1. Permalink

    For a Lua-facing wrapper, I would keep allocation ownership in the C host. The script requests growth, then gets failure or access to the replacement. Failure leaves the existing buffer available for another attempt. Success means obtaining a fresh view before continuing. Can the wrapper avoid exposing raw addresses at all? That would make the handoff easier to follow than asking scripts to remember which saved pointers expired.

Other sides of the same question

  1. What survives a catalog reload?

    An API returns a slice of names, but the backing allocation may be released or replaced before the caller finishes reading. T…