Prabal Kajla
Prabal Kajla

Reputation: 125

strcat_s after strcpy_s gives Error

I am trying to concatenate two strings in C++ using VS 2013. Below is the code:

char *stringOne = "Hello";
char *stringTwo = " There!"; 
char *hello = new char[strlen(stringOne) + strlen(stringTwo) + 1];
strcpy_s(hello, strlen(hello), stringOne);
//hello[strlen(stringOne)+1] = '\0';
strcat_s(hello, strlen(hello), stringTwo);//<-----Does not return from this call

If the strcat_s statement is commented,it runs fine and *hello contains "Hello".

But with it, VS says the application has triggered a breakpoint after showing:

Expression: (L"String is not null terminated" && 0)

It doesn't work anyway I've tried. The closest existing question I found is here. As prescribed, manually setting the last character as null doesn't help either.

Any ideas anyone?

Upvotes: 0

Views: 1017

Answers (1)

Ext3h
Ext3h

Reputation: 6391

strlen(hello) is the wrong string length, respectively it's complete garbage at that time since hello isn't even initialized yet.

The expression strlen(stringOne) + strlen(stringTwo) + 1 which you had used to allocate the target buffer would had been the appropriate length to pass.

Also better get used to checking the return values of the _s functions, because then you would have known that already the first function call had failed.

Upvotes: 1

Related Questions