user13977876
user13977876

Reputation:

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

Upvotes: 0

Views: 179

Answers (3)

Joshua
Joshua

Reputation: 43317

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.

Upvotes: 2

Yogesh C K
Yogesh C K

Reputation: 34

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

Upvotes: -1

Nate Eldredge
Nate Eldredge

Reputation: 58473

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.

Upvotes: 1

Related Questions