Is this all correct?
None of the examples are correct.
char* dest = new char;
You've allocated a single char
. The only string that it can represent is the empty string.
char* c = new char;
c = "Richard";
By assigning c
to point elsewhere, you've lost the pointer value that was returned by new
. As a consequence, you can no longer pass that value to delete
. This is called a memory leak.
Furthermore, since C++11 this is ill-formed since string literals are no longer convertible into pointer to non-const char. Being ill-formed means that a compiler is not required to compile your program, and instead it is required to issue you a diagnostic message informing you about the ill-formedness.
strcpy_s(dest, strlen(c) + 1,c);
You're supposed to pass the size of the destination buffer; not the size of the source data. In this case the destination buffer is too small, but because you passed the wrong value, the error is not caught and the behaviour is undefined.
As I mentioned, pass the size of the destination buffer:
auto error = strcpy_s(dest, 1, "Richard");
This safely results in an error instead of undefined behaviour - or it might safely abort the program or do something else depending on implementation. You can control the constrain handler to have your desired behaviour.
Of course, you might want to allocate sufficient memory so that the copy works:
std::size_t destsz = 1024;
char* dest = new char[destsz];
You know the size that you allocated. Simply pass that to strcpy_s
:
auto error = strcpy_s(dest, destsz, "Richard");
Don't forget to clean up:
delete[] dest;
P.S. The C++ standard library doesn't provide strcpy_s
. It is a non-standard function. It is standard in C language only (but it is optional for an implementation to provide it).
P.S.S Don't use new
to allocate strings. Use std::string
in C++. With std::string
you can copy like this:
std::string c = "Richard";
std::string dest = c;
It will be much harder to leak memory or make more serious bugs with this approach.