3

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;
}

1 Answers1

11

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:

char *x = "bbb";
x[0] = 'a';

I think you may be confusing it with:

char x[] = "bbb";
x[0] = 'a';

which is valid since it creates an array that you are allowed to modify. But what yours gives you:

char* target[2] = {"cccc","bbbbbbbbbb"};

is an array of pointers, all of which point to non-modifiable memory.

If you were to try:

char t0[] = "cccc";
char t1[] = "bbbbbbbbbb";
char* target[2] = {t0, t1};
strcpy(target[1],src);

you would find that it works since target[1] now points to t1, which is modifiable.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Then why does this work? `#include static char src[] = "aaa"; int main() { char* target = "bbbbbbbbbb"; strcpy(target,src); return 0; } ` – confusedDespiteKnowingBetter Feb 22 '11 at 02:55
  • 4
    @confused: If that works, it's purely by accident. It's _still_ undefined behaviour and you shouldn't do it, since _anything_ may happen - sometimes the "anything" may be that it just works, but switching to a different system, or compiler, or compiler flags or even running after 9pm or on a blue moon may cause your code to crash. For example, that _exact_ code causes "Segmentation fault" on my Ubuntu 10.04 box. – paxdiablo Feb 22 '11 at 02:59