I want to print "Hello - World" by using two char pointers but I have a "Segmentation fault (core dumped)" problem.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define Hyphen " - "
int main()
{
char* x="Hello";
char* y="'World'";
strcat(x, Hyphen);
strcat(x, y);
printf("%s",x);
return 0;
}
You're essentially trying to use a string literal as the destination buffer for strcat()
. This is UB for two reasons
Solution: You need to define an array, with sufficient length to hold the concatenated string, and use that as the destination buffer.
One example solution by changing the code:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define Hyphen " - "
#define ARR_SIZE 32 // define a constant as array dimention
int main(void) //correct signature
{
char x[ARR_SIZE]="Hello"; //define an array, and initialize with "Hello"
char* y="'World'";
strcat(x, Hyphen); // the destination has enough space
strcat(x, y); // now also the destination has enough space
printf("%s",x); // no problem.
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With