The following code seems to segfault and I cannot figure out why.
#include <string.h>
static char src[] = "aaa";
int main()
{
char* target[2] = {"cccc","bbbbbbbbbb"};
strcpy(target[1],src);
return 0;
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because
target[1]is a pointer to"bbbbbbbbbb"and you are not allowed to modify string constants. It’s undefined behaviour.It’s no different to:
I think you may be confusing it with:
which is valid since it creates an array that you are allowed to modify. But what yours gives you:
is an array of pointers, all of which point to non-modifiable memory.
If you were to try:
you would find that it works since
target[1]now points tot1, which is modifiable.