Solved: 02 - Hello World!
This commit is contained in:
@@ -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
|
||||||
|
|||||||
Reference in New Issue
Block a user