One of the main reasons to allocate memory on the heap is to give it a lifespan that is not determined by the scope of a single function. Instead of deleting memory that it allocates, a function can return the address of it (or otherwise pass off the address to other code). If it does pass the address off to other code, that implies that the other code is now responsible for the memory.
To return the address of heap based memory, the function can just return the pointer it is using to store that address. The caller can store the returned memory address into a pointer of the correct type. It now βownsβ that memory and is responsible for deleting it when it is no longer needed. We can also pass the memory address to other functions, allowing them to use the memory. As we do so, we must decide which code now βownsβ the memory and is responsible for deleting it. The Codelens below demonstrates:
There is one part of the Codelens animation that is inaccurate. When the makeMemory function returns, it looks like the memory on the heap disappears. That is just an artifact of the animation. It is still there. By comparing the memory addresses reported for p1 and returnedPointer, we can see that they are the sameβthe memory never actually went away.
Notice that borrowMemory changes the value of the memory that was shared with it. When we return to main, the returnedMemory pointer still has the same address, but now that memory location contains the value 10.
Fix the function takeoverMemory so that the program runs without errors from AddressSanitizer. main will not use the memory after passing the address to takeoverMemory and so the code assumes that takeoverMemory will be responsible for deleting the memory.