Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use strcat function with char pointer [duplicate]

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;
}
like image 228
Ran Marashi Avatar asked Oct 27 '22 15:10

Ran Marashi


1 Answers

You're essentially trying to use a string literal as the destination buffer for strcat(). This is UB for two reasons

  • You're trying to modify a string literal.
  • You're trying to write past the allocated memory.

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;
}
like image 184
Sourav Ghosh Avatar answered Nov 02 '22 10:11

Sourav Ghosh