Search code examples
c++linuxsegmentation-faultappendchars

Segmentation fault when appending two chars - C++


I am trying to append two chars but for some reason I am getting a segmentation fault.

My code is like;

#include <string.h>
char *one = (char*)("one");
char *two = (char*)("two");

strcat(one, two);

and I seem to be getting a segmentation fault at strcat(one, two), why is that?


Solution

  • http://www.cplusplus.com/reference/clibrary/cstring/strcat/

    the first parameter to strcat, must be big enough to hold the resulting string

    try:

    //assuming a,b are char*
    char* sum = new char[strlen(a) +strlen(b)+1];
    strcpy(sum,a);
    strcat(sum,b);