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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With