Skip to main content

Section 22.7 Passing Memory with Pointers

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.

Insight 22.7.1.

When a function calls new, it should either delete the memory, or pass off responsibility for deleting it to another part of the program.
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:
  • Creating memory in makeMemory.
  • Passing responsibility for that memory to main with a return.
  • Main passing that memory to borrowMemory. Here we have decided that main β€œowns” the memory still.
  • Main deleting the memory when it is done using it.
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.
Listing 22.7.1.
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.

Activity 22.7.1.

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.

Checkpoint 22.7.1.

Construct a program that:
  • Starts with the makePerson function It allocates a person on the heap and returns the memory address of the new memory.
  • Next has a printPerson function that takes a pointer to a Person object and prints its name. It is assumed to just β€œborrow” the memory.
  • The main function will be assumed to β€œown” the memory for the Person objects it gets back from makePerson.
You have attempted of activities on this page.