Solved: 02 - Hello World!

This commit is contained in:
David Gil de Gómez Pérez
2026-08-11 18:23:17 +03:00
parent 8de2e83c0b
commit 6af86468d0
+13 -3
View File
@@ -1,11 +1,21 @@
#include "hello_world.hpp" #include "hello_world.hpp"
#include <cstring>
#include <string>
namespace fundamentals { namespace fundamentals {
auto greet(const char* name) -> const char* { auto greet(const char* name) -> const char* {
// TODO: Return a static string in the format "Hello, <name>!" const auto n = std::string(name);
(void)name; const auto c = "Hello, " + n + "!";
return "Hello, World!"; // 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 } // namespace fundamentals