-2

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...

4 Answers4

3

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());
Ðаn
  • 10,934
  • 11
  • 59
  • 95
3

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!

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
3

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.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
2

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");
KonstantinL
  • 667
  • 1
  • 8
  • 20
  • 4
    You don't need the strcpy() - `char test[128] = "hello";` does the job. –  Feb 10 '17 at 14:05