Definition
A borrowed pointer is a pointer that its holder may use for an agreed, limited time but may not use to free the object it points to. A pointer is a value that holds the memory address of an object. Freeing an object gives its memory back; that duty belongs to the owner of the object. The owner lends the pointer and keeps the object alive until the agreed time ends, and the borrower then stops using the pointer. The usual time is one function call.
The idea
Passing a pointer to a function is cheap, because the data is not copied. The trouble is that a pointer cannot be taken back. The caller means “look at this while I wait”, but the function now knows the address and can keep it. Take a caller that holds 4 bytes in a local variable and passes their address to a function. If the function reads the bytes and returns, all is well. If the function stores the address for later, the caller soon returns, the local variable ceases to exist, and the stored address points into memory that other code is now using.
Lending a car for the afternoon is a fair picture. The borrower may drive it, may not sell it, and must bring it back by the evening; the owner promises not to scrap it meanwhile. The picture stops being accurate in one respect. A car that is not returned is missed. A pointer is never returned: the borrower still has the address after the loan ends, and nothing stops the borrower from using it.
How it works
A loan of a pointer is defined by four statements. The C compiler checks only part of the second, so the documentation of the function must state the rest.
Which bytes. The pointer and a length.
Which operations. Reading only, or reading and writing. The C keyword
constin the type of the parameter forbids writing through that pointer.How long. Until the function returns, unless the documentation names a later point.
What the owner promises. To keep the object alive, and not to change or move it, for that time.
A correct loan runs in this order.
The loan begins: the owner calls the function and passes the pointer.
The borrower reads or writes within the permitted bytes.
The loan ends: the function returns, and the borrower keeps no copy of the pointer.
The owner is again free to change, move or free the object.
Work that happens after the function has returned is called asynchronous work. A common form is an asynchronous callback §14.22: a function that is registered now and called later, when some event occurs. A loan that ends at the return cannot cover such work. Four designs can.
Copy. Before returning, the function copies the bytes into memory that it owns, and frees that memory when the work is done.
Transfer. The caller hands over ownership §4.2, and the receiver frees the object when the work is done.
Share. The object carries a count of its users and is freed when the count reaches 0. The function adds itself to the count before returning and removes itself after the work. This scheme is reference counting §9.22.
A longer loan, stated in writing. The documentation names a later end. The libuv library, a library for asynchronous input and output, does this for its function
uv_write: the memory pointed to by the buffers must remain valid until the callback gets called.
Worked example
A function caller has a local array §14.5 A of 4 bytes at the invented address 0x20000100. The bytes are 01 02 03 04.
A correct loan. caller calls sum(A, 4). The function sum reads the 4 bytes, computes and returns 10. All four reads happen between the call and the return.
A broken loan. caller calls send_later(A, 4). The documentation says that send_later borrows A only for the call, but the function is written as follows.
send_laterstores the address0x20000100and the length 4 in a queue of pending work, and returns. The loan has ended.callerreturns. A was a local variable, so A no longer exists.The program calls another function, whose local variables occupy the same memory. That function writes the bytes
AA BB CC DDat0x20000100.The queued work runs, reads 4 bytes at
0x20000100and sendsAA BB CC DD, not01 02 03 04.
The read in step 4 comes after the end of the loan and after the end of A. Without step 3 the old bytes would still be in place, and the program would appear to work.
The repair by copying. send_later allocates 4 bytes of its own, called B, copies 01 02 03 04 from A into B before it returns, and puts the address of B in the queue. The copy happens inside the loan. The queue owns B and frees B after the work has run or has been canceled.
Stated precisely
A loan is the span of execution between two events that the documentation of the function fixes: the start of the loan and the end of the loan. The loan is honored when four conditions hold.
Every access that the borrower makes through the pointer, or through any copy of it, happens between the start and the end of the loan.
The object exists from the start of the loan to its end. That is the duty of the owner.
The borrower performs only the permitted operations on the permitted bytes, and never frees the object.
If the documentation says that the object stays unchanged, no part of the program modifies it during the loan.
When the documentation does not state the end of the loan, the borrower must assume the earliest possible end: the return of the function that received the pointer.
The keyword const covers less than it seems to. In the declaration const uint8_t *p, which declares a pointer to bytes, it forbids writing to the bytes through p. It does not stop other code from changing the bytes through a different pointer, and it says nothing about how long p may be used.
Limits and common mistakes
The type does not show the loan. A borrowed pointer and an owned pointer have the same C type. Only the documentation tells them apart. In the Rust language, where making a reference to a value is called borrowing, the compiler checks that no reference is used after its value is gone. The C interface of the Python §12.23 language calls a reference that its user does not own a borrowed reference.
The owner can break the loan by moving the object. A pointer to an element inside a buffer that can grow becomes invalid when the owner enlarges the buffer, because enlarging may move the contents to a new address.
Copying has costs. The copy needs memory, and the allocation can fail.
Canceled and failed work still holds what it was given. Every way the later work can end, including cancellation §9.29 and error, must free its copy or the object that was transferred to it, give up its share, or tell the owner that a longer loan is over.
Questions answered
Can an asynchronous callback retain a pointer passed only for the duration of a call?
No. A pointer passed only for the duration of a call is a borrowed pointer whose loan ends when the call returns. An asynchronous callback is a function that runs at some later time, after that return. By then the owner of the object, the part of the program responsible for freeing it, is free to change, move or free the object, so the retained pointer may point to memory that holds something else.
If the callback needs the data, the design must provide one of four things: a copy of the data, made during the call and owned by the code that runs the callback; a transfer of the object to that code, which then frees it; a counted share in the object, so that the object is freed only after its last user is done; or a written rule that the caller keeps the object alive until the callback has run. The design must also say who frees the data when the callback is canceled or never runs.
Related entries: Object lifetime (§4.1), Ownership (§4.2), Reference counting (§9.22), Use-after-free (§4.6), Asynchronous completion (§9.28), Callback (§14.22). Further reading: [78].