1

I implement a simple strcpy, but when i run it , it always give a segmentation fault. Please help!

Below is my code:

#include <stdio.h>

char* mystrcpy(char *dst, char *src){
    char *ptr = dst;
    while (*src !='\0') {
        *dst = *src;
        dst++;
        src++;
    }
    return ptr;
}

int main (int argc, char **argv) {
    char *str1 = "abc";
    char *str2 = "def";
    char *str3 = NULL;
    str3 = mystrcpy(str2, str1);
    printf("str2 now is %s", str2);
    printf("str3 is %s", str3);
    return 0;
}
keparo
  • 33,450
  • 13
  • 60
  • 66
  • There is no space to store string contents in `str1` and `str2`. try `char str1[100] = "abc"` and `char str2[100] = "def"` and `char str3[100] = ""` – Stan Jul 23 '11 at 09:22
  • 4
    Also note that the standard `strcpy` null terminates the destination. You probably want yours to do the same. – CB Bailey Jul 23 '11 at 09:33
  • The fact that you can write that loop as `while(*src) *dst++=*src++;` is by many considered one of the greatest strengths of C. I understand that such code terrifies newbies, but to us, who have been staring at such code for many, many years, its denseness comes across as simplicity and is pure beauty. Also note what Charles said. A `do ... while` loop would be better. – sbi Jul 23 '11 at 09:36

2 Answers2

9

These are read-only. Writing to them results in undefined behavior.

char *str1="abc"; /* Read-only. */
char *str2="def";

while (*src !='\0') {
    *dst = *src; /* Writes into read-only memory. */

See this C FAQ:

String constants are in fact constant. The compiler may place them in nonwritable storage, and it is therefore not safe to modify them.

And another explanation. You should try

char str1[]="abc";
char str2[]="def";
cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • 1
    Right. But unlike in C++, string literals are of type "char[]", not "const char[]", so the compiler typically won't warn you when you try to modify a string literal. This is a bit inconsistent, but it was defined that way to avoid breaking existing code (from before "const" was added to the language). You can help the compiler out by declaring `const char *str1 = "abc"`. – Keith Thompson Jul 23 '11 at 21:23
-3

while( *src !='\0'){ *dst=*src;

You need to dereference your pointers here, using &, not *

EDIT:

Looks like I'm having my own personal cranial segmentation fault, here - too early in the morning!

cnicutar's explanation (assigning a pointer to a string constant with char *str2 = "def";, and then trying to write to that location) is much more plausible...

Richard Inglis
  • 5,888
  • 2
  • 33
  • 37