Program aborts when using strcpy on a char pointer? (Works fine on char array)

John Smith picture John Smith · Apr 13, 2011 · Viewed 11k times · Source

I'm perplexed as to why the following doesn't work:

char * f = "abcdef";
strcpy(f, "abcdef");
printf("%s",f);

char s[] = "ddd";
strcpy(&s[0], "eee");
printf("%s", s);

In both examples strcpy received a char * yet on the first example it dies a horrible death.

Answer

Erik picture Erik · Apr 13, 2011

"abcdef" and "ddd" are string literals which may reside in a read-only section of your address space. char s[] = "ddd" ensures this literal is copied to stack - so it's modifiable.