1

I wrote a string copy program using pointer,but it got a segmentation fault,don't know why.

Thanks

here is my code:

#include<stdio.h>

void strcp(char *s,char *t){
   while(*s++=*t++)
        ;
     }

void main(){
  char *d="this is destination";    
  char *s="this is source";  
  strcp(d,s);
  while(d++){
     printf("%s  " ,*d);
   }

    return;
  }
Ziu
  • 649
  • 1
  • 8
  • 20
  • Your second parameter, as well as both of the literals, should be `const char *` (or `char[]` for the literals). Your main function would be better off as `int main()` as well. You probably don't want the while loop to print, either. Just `printf("%s ", d);` – chris May 23 '13 at 02:44

2 Answers2

1

d is pointing to a string literal it is undefined behavior to write to a string literal. You could alternatively define d as follows:

char d[]="this is destination"; 

Also you need to fix the printf and loop from this:

while(d++){
  printf("%s  " ,*d);
}

to this:

printf("%s  " ,d);

and you can remove the loop. Finally, main should always return an int:

int main()
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
0

Even if you weren't passing in literals, if t is longer than s then your pointer runs off the end.

stark
  • 12,615
  • 3
  • 33
  • 50