简体   繁体   中英

Simple C program using <string.h> methods not running

I have the following code.

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

int main()
{
    char first[] = "foo";
    char last[] = "bar";
    
    strcat(first, last);
    
    printf("%s\n", first);

    return 0;
}

it compiles but when I run it I get the following error:

zsh: illegal hardware instruction./output/strfunc.out

For reference I'm using clang to compile the code:

Apple clang version 12.0.5 (clang-1205.0.22.9)
Target: x86_64-apple-darwin20.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

I can't seem to be able to use any of the methods associated with <string.h>. I have looked online but found nothing, any ideas?

char first[] = "foo";

That tells the compiler to create an array that is sized exactly to fit the initializer string. It has no space for any more characters to be added. So trying to add a string to the end with strcat results in a buffer overflow and hence Undefined Behaviour.

One solution is to explicitly size the array:

#define MAX_SIZE 32
char foo[MAX_SIZE] = "foo";

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