简体   繁体   中英

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);
}

Considering the most likely implementation of strcat , don't do it. In general, it's a bad idea to pass a function the same parameter for both input and output. In fact, let's put this a little better. Unless the function says its defined, it's not defined, so don't do it.

Try this:

size_t n = strlen(num);
memmove(num + n, num, n + 1);

memmove is a nice function that's designed for overlapping inputs and outputs.

You can't use strcat to concatenate two strings which overlap, which includes the case when they are the same string.

You'll have to write your concatenation routine by hand, or think about a solution based on memcpy .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM