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

Time:10-09

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?

CodePudding user response:

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";
  • Related