-3
#include <stdio.h>
#include <string.h>

int main()
{
    char s1[] = "harry";
    char s2[] = "ravi";
    char s3[54];

    puts(strcat(s1, s2));
    
    strcpy(s3 ,strcat(s1, s2));
    puts(s3);
    
    return 0;
} 
  

this is the error that I will get

cd "/Users/deepkar/Desktop/C_COURSE/" && gcc tut27.c -o tut27 && "/Users/deepkar/Desktop/C_COURSE/"tut27
deepkar@Deeps-Air C_COURSE % cd "/Users/deepkar/Desktop/C_COURSE/" && gcc tut27.c -o tut27 && "/Users/deepkar/Desktop/C_COURSE/"tut27
zsh: illegal hardware instruction  "/Users/deepkar/Desktop/C_COURSE/"tut27
deepkar@Deeps-Air C_COURSE % 
Gerhardh
  • 11,688
  • 4
  • 17
  • 39
Deepkr09
  • 1
  • 1
  • 4
    `s1` doesn't have room for the combined string. The behavior is undefined. – HolyBlackCat Jan 01 '22 at 12:00
  • 3
    The [`strcat`](https://en.cppreference.com/w/c/string/byte/strcat) function doesn't create a new string. It appends the second string to the first string. The first string *must* have space enough for the combined strings, including null-terminator. – Some programmer dude Jan 01 '22 at 12:02
  • See this string handling FAQ here: [Common string handling pitfalls in C programming](https://software.codidact.com/posts/284849) – Lundin Jan 01 '22 at 12:45

1 Answers1

0

The problem come from your code having undefined behavior:

You call strcat(s1, s2); twice, attempting to copy the characters from s2 at the end of the array pointed to by s1, but s1 already contains a string "harry" that along with its null terminator fills the array completely, the definition char s1[] = "harry"; giving it a length of 6 bytes. strcat writes beyond the end of the array s1, overwriting important data, such as the return address for function main. The observed behavior is consistent with the CPU branching to an invalid address.

You can copy s1 to s3 and catenate s2 to that instead.

chqrlie
  • 131,814
  • 10
  • 121
  • 189