Для строк в стиле C это может быть
char* // we want return a mutable string? OK
AddNewlineToString(
const char* s // We don't need to change the original string, so it's const.
)
{
const size_t MAX_SIZE = 1024; // if it's a mutable string,
// it should have a known capacity.
size_t len = strlen(s);
if(len + sizeof("\n") // To avoid the magic number "2".
> MAX_SIZE)
return NULL; // We don't know what to do with this situation,
// the user will check the result and make a decision -
// to log, raise exception, exit(), etc.
// static // We want a thread-safe result
char* buf = new char[1024]; // so we allocate memory in the heap
// and it's C-language-string but not C language :)
memcpy(buf, s, len); // Copy terminating zero, and rewrite it later? NO.
memcpy(buf + len, "\n", sizeof("\n")); // The compiler will do it in one action like
// *(int16_t*)(buf + len) = *(int16_t*)"\n";
// rather than two assignments.
return buf;
}