6

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;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Ran Marashi
  • 71
  • 1
  • 3

2 Answers2

3

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;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

String literals are immutable in C (and C++).

To concatenate one string to another string the last string (that is a character array) shall have enough space to accomodate the first string.

So ons of solutions using pointers is to allocate dynamically enough memory for a (result) character array and then concatenate the strings inside the character array.

For example

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#define Hyphen " - "

int main( void )
{
    const char *x = "Hello";
    const char *y = "'World'";

    size_t n = strlen( x ) + strlen( y ) + strlen( Hyphen ) + 1;

    char *s = malloc( n );

    strcpy( s, x );
    strcat( s, Hyphen );
    strcat( s, y );

    puts( s );

    free( s );

    return 0;
}

The program output is

Hello - 'World'

If you want to exclude the single quotes around the string "'World'" then the code can look the following way.

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#define Hyphen " - "

int main( void )
{
    const char *x = "Hello";
    const char *y = "'World'";

    size_t n = strlen( x ) + ( strlen( y ) - 2 ) + strlen( Hyphen ) + 2;

    char *s = malloc( n );

    strcpy( s, x );
    strcat( s, Hyphen );
    strcat( s, y + 1 );

    s[strlen( s ) - 1] = '\0';
    // or
    // s[n - 2] = '\0';

    puts( s );

    free( s );

    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335