Latest Posts

Topic: Returning a pointer to a local array?

RichHolton
Avatar
Joined: 2022-09-08, 20:44
Posts: 23
Ranking
Pry about Widelands
Location: Rockford, Illinois, USA
Posted at: 2022-10-20, 16:27

Either I have found a potential bug, or my understanding of C++ arrays is lacking. I hope someone can let me know which.

In base/log.cc take a look at the function get_output_directory (line 52). This is part of a _WIN32 block.

The function declares an array of char (or wchar_t) named path. It fills that array using GetModuleFileName(), then makes some modifications, and returns a pointer to path.

Isn't path allocated from the stack? Put a different way, isn't the lifetime of path limited to the duration of the function?

If so, returning a pointer to path is at least dangerous.

The function's only use is on line 143, to create a new WindowsLogger.

Thanks for any feedback.


Rich Holton

Top Quote
Nordfriese
Avatar
Joined: 2017-01-17, 18:07
Posts: 1728
OS: Ubuntu MATE 22.10
Version: Latest master
Ranking
One Elder of Players
Location: 0x55555d3a34c0
Posted at: 2022-10-20, 16:39

Forget my previous post. The function returns std::string so the return statement is an implicit type conversion. String constructor makes a deep copy on the heap. So it's safe.


Top Quote
RichHolton
Avatar
Joined: 2022-09-08, 20:44
Posts: 23
Ranking
Pry about Widelands
Location: Rockford, Illinois, USA
Posted at: 2022-10-20, 19:32

I didn't know that there was an implicit conversion to String on a return. Thanks for educating me.


Rich Holton

Top Quote