I trying strcat_s function and crashing application. How to work this code?
char *test = "hello ";
strcat_s(test, strlen(test), "guys");
// like output "hello guys" but application crashing...
I trying strcat_s function and crashing application. How to work this code?
char *test = "hello ";
strcat_s(test, strlen(test), "guys");
// like output "hello guys" but application crashing...
Since you're writing C++, you should be using std::string, not char*.
std::string test = "hello ";
test += "guys;
And if you need to pass that string to existing C++ code as a pointer, use the c_str() method:
extern void foo(const char*);
foo(test.c_str());
You're trying to modify a string literal. That is not allowed.
Your compiler should at least be warning you about that char* test, which should be const char* test to enforce immutability. In fact, since C++11, your code won't even compile!
In C++03
char *test = "hello ";
Is a deprecated conversion of a const char[N] to a char*. Trying to modify it with strcat is undefined behavior.
In C++11 and above You have ill formed code.
char *test = "hello ";
Is not legal C++. The type of "hello " is a const char[N]. That means when you call strcat you try to modify a constant string. If you turn up your warning level to compiler should tell you this.
You really should be using std::string and then you could have
std::string test = "hello ";
test += "guys;
And it will work just fine.
The pointer test points to read-only memory. Modifing the read-only memory causes app crash.
This will work:
char test[128];
strcpy(test, "hello ");
strcat_s(test, strlen(test), "guys");