Returning local data from functions in C and C++ via pointer

Your friend is wrong.

name is returning a pointer to the call stack. Once you invoke printf, there’s no telling how that stack will be overwritten before the data at the pointer is accessed. It may work on his compiler and machine, but it won’t work on all of them.

Your friend claims that after name returns, “nothing happens except printing it”. printf is itself another function call, with who knows how much complexity inside it. A great deal is happening before the data is printed.

Also, code is never finished, it will be amended and added to. Code the “does nothing” now will do something once it’s changed, and your closely-reasoned trick will fall apart.

Returning a pointer to local data is a recipe for disaster.

Leave a Comment