cstrcat

Error: 'zsh: illegal hardware instruction' in C


I was learning string.h header file and wrote a simple program to concatenate two strings.

The simple C program

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

int main()
{
   
    char str1[] = "sandeep";
    char str2[] = "sahani";
    strcat(str1, str2);
    printf("%s %s", str1, str2);

    return 0;
}

Got an error which says:

"/Users/sandeepsahani/Desktop/Sandeep Sahani/Basic Programming/ C programming/Basic Programs/DS/"stringConcat zsh: illegal hardware instruction

What's wrong with my code?


Solution

  • couple of problems here:

    1. char arrays that are initialized with static data should be treated as readonly, and not updated. You can't just add more characters to the end of it. It may work, or may generate an error. Undefined behavior.
    2. you have to allocate enough memory for the target string to hold all the concatenations.
    int main()
    {
           
        char str1[] = "sandeep";
        char str2[] = "sahani";
        char str3[100] = {0};
        
        strcat(str3, str1);
        strcat(str3, str2);    
        printf("%s %s  %s", str1, str2,str3);
    
        return 0;
    }