Reputation:
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
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
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
Reputation: 58473
You can't use strcat
to concatenate two strings which overlap, which includes the case when they are the same string.
https://en.cppreference.com/w/c/string/byte/strcat: "The behavior is undefined if the strings overlap."
C17 7.24.3.1 (2): "If copying takes place between objects that overlap, the behavior is undefined."
You'll have to write your concatenation routine by hand, or think about a solution based on memcpy
.
Upvotes: 1