Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using strcat inside another function: Segmentation fault (core dumped)

    static void foo(unsigned char *cmd)
    {
        strcat(cmd, "\r\n");
        printf("\r\nfoo: #%s#", cmd);

    }
    int main()
    {
        foo("test");
        return 0;
    }

Compiler says Segmentation fault (core dumped) What is the actual problem here?

like image 445
HardCoder Avatar asked Jul 05 '26 03:07

HardCoder


2 Answers

You have undefined behaviour. You are not allowed to modify string literals. cmd points to a string literal and strcat() attempts concatenate to it, which is the problem.

  int main(void)
    {
        char arr[256] = "test";
        foo(arr);
        return 0;
    }

You generally need to be careful when using strcpy() and strcat() etc in C as there's a possibility that you could overflow the buffer. In my example, I used an array size of 256 which is more than enough for your example. But if you are concatenating something of unknown size, you need to be careful.

like image 59
P.P Avatar answered Jul 06 '26 15:07

P.P


In C string literals (like "test") are read-only arrays of characters. As they are read-only they can't be modified. As they are arrays they have a fixed size. You both try to modify the string literal, and extend it.

like image 38
Some programmer dude Avatar answered Jul 06 '26 17:07

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!