Files
cpp-course/modules/01_fundamentals/src/hello_world.cpp
T

22 lines
739 B
C++

#include "hello_world.hpp"
#include <cstring>
#include <string>
namespace fundamentals {
auto greet(const char* name) -> const char* {
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