Search code examples
arrayscstringsegmentation-faultstring-concatenation

Segmentation fault while using strcat(num, num) to concatenate string to itself


I used strcat function to concatenate "1" and "1" so that the result is "11" but I'm getting a segmentation fault.

My code is below:

#include <stdio.h>
#include <string.h>
int main(){
  char num[10] = "1";
  strcat(num, num);
  printf("%s", num);
}

Solution

  • You need two char[] one as source and other for destination, where destination array must be initialized and have enough space to accommodate source length.

    #define DEST_SIZE 40
    
    int main(){
      char num[10] = "1";
      char dest[DEST_SIZE] = "1"; //Destination with null characters after "1"
      strcat(dest,num);
      printf(dest);
      return 0;
    }
    

    For detailed explanation about different scenarios : here