Why does the following happen:
char s[2] = "a";
strcpy(s,"b");
printf("%s",s);
–> executed without problem
char *s = "a";
strcpy(s,"b");
printf("%s",s);
–> segfault
Shouldn’t the second variation also allocate 2 bytes of memory for s and thus have enough memory to copy "b" there?
No,
char *sis pointing to a static memory address containing the string"a"(writing to that location results in the segfault you are experiencing) whereaschar s[2];itself provides the space required for the string.If you want to manually allocate the space for your string you can use dynamic allocation:
Don’t forget to
free()your string afterwards.