Search code examples
carrayspointerscstringstrcpy

Why does C's strcpy fail with doubly indexed arrays?


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

Solution

  • 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.