简体   繁体   中英

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?

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;
}

If you don't specify the size of an array, the size is just enough to hold the values it's being initialized with. So str1 only has 8 characters (7 characters plus the null terminator). That's not enough room to add sandeep to it.

If you want to concatenate to it, you need it to have room for the additional string. Since str2 is 6 characters, str1 needs at least 14 characters. So change it to:

char str1[14] = "sandeep";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM