Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

strcpy

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.

like image 738
John Smith Avatar asked Apr 13 '11 07:04

John Smith


2 Answers

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

like image 91
Erik Avatar answered Sep 30 '22 02:09

Erik


char * f = "abcdef"; defines a char pointer to "abcdef" which is located in read-only area so you can't write to this place

char s[] = "ddd"; defines a char array on the stack which is writable.

like image 29
MByD Avatar answered Sep 30 '22 03:09

MByD