diff --git a/modules/01_fundamentals/src/hello_world.cpp b/modules/01_fundamentals/src/hello_world.cpp index 2a24a75..c3bbfbf 100644 --- a/modules/01_fundamentals/src/hello_world.cpp +++ b/modules/01_fundamentals/src/hello_world.cpp @@ -1,11 +1,21 @@ #include "hello_world.hpp" +#include +#include + namespace fundamentals { auto greet(const char* name) -> const char* { - // TODO: Return a static string in the format "Hello, !" - (void)name; - return "Hello, World!"; + const auto n = std::string(name); + const auto c = "Hello, " + n + "!"; + // LESSON: Never return pointers to local objects -> dangling -> undefined behavior + // NO! --> return c.c_str(); + // The destructor will be called when c goes out of scope, destroying the object and freeing its memory + // This is shit C++ and should use std::string instead as a return value + const auto p = new char[c.length() + 1]; // Give space for the null terminated pointer + strcpy(p, c.c_str()); + return p; + // TL;DR -> Never use C-style strings if possible } } // namespace fundamentals