Instead of passing dataBuf as a parameter to chunk_new, can't you declare it locally in chunk_new and deallocate the buffer after you copy it into the bson object? It seems a lot simpler – it seems you transfer ownership back to the caller, only so they can free it.