Why does C strcpy fail with double-indexed arrays?

The following code seems to be segfault, and I cannot understand why.

#include <string.h>

static char src[] = "aaa";

int main()
{
   char* target[2] = {"cccc","bbbbbbbbbb"};
   strcpy(target[1],src);
   return 0;
}
+3
source share
1 answer

Because it target[1]is a pointer to "bbbbbbbbbb", and you are not allowed to change string constants. This behavior is undefined.

This is no different from:

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

I think you can be confusing:

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

which is valid since it creates an array that you can modify. But what gives you:

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

represents an array of pointers, all of which point to unmodifiable memory.

If you tried:

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

You will find that it works, as it target[1]now points to t1which can be changed.

+11
source

Source: https://habr.com/ru/post/1793761/


All Articles