1

I am trying to understand pointers and here is a program in K&R that I am trying to implement. The program is strcpy with code from KR.

/*strcpy: copy t to s; pointer version 3*/
void strcpy(char *s, char *t){

while(*s++ = *t++)     
    ;              
}

So to implement this program, I add

#include<stdio.h>
int main(){

    char *s="abc", *t="ABC" ;

    strcpy(s,t);
    printf("%s\n",t);

    printf("%s\n", s);
    return 0;
}

However I am getting segmentation error when I run it. I am sure I am missing something but not quite sure what.

Thanks!

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
DBS
  • 131
  • 5
  • 1
    possible duplicate of [Modifying String Literal](http://stackoverflow.com/questions/5464183/modifying-string-literal) – Carl Norum Jul 22 '13 at 05:28
  • 1
    possible duplicate of [Why do I get a segmentation fault when writing to a string?](http://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string) – Krishnabhadra Jul 22 '13 at 05:28
  • Possible duplicate of http://stackoverflow.com/questions/17111140/string-in-function-parameter – Jeyaram Jul 22 '13 at 06:01

2 Answers2

8
char *s="abc", *t="ABC" ;

string literals are not modifiable, however, a char array can be modified, so change it to :

char s[] ="abc", *t="ABC" ;
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
7

Literal string values are stored in a read-only memory page; they cannot be modified.

Joni
  • 108,737
  • 14
  • 143
  • 193