-1

I'm trying to implement strcpy within my main but I'm not sure why I'm segfaulting on the first while loop. Could someone shed light?

int main()
{
    const char* src = "this is a test";
    char* dest = "abcdefgqwerty";
    char* head = dest;
    while(*dest++ = *src++);
    while(*head++)
    {
        printf("%c", *head);
    }

    return 0;
}
Mozbi
  • 1,399
  • 1
  • 17
  • 25
  • 1
    `char* dest = "abcdefgqwerty";` is read-only. – Chnossos Sep 06 '14 at 22:49
  • Well, if you mean you truly want to implement your version of `strcpy` that mimics the runtime function, then what you implemented is correct. The runtime function will also go haywire on bad input. – PaulMcKenzie Sep 06 '14 at 23:07

2 Answers2

1

These is not enough room in the destination for what you are copying. The declaration of dest only contains 14 bytes but you need 15.

Dwayne Towell
  • 8,154
  • 4
  • 36
  • 49
1

dest variable points to the string literal, which in reality resides in read-only memory region. That's why you can't copy into it.

To test your strcpy() implementation, I'd recommend declaring strings as arrays:

char dest[256] = "abcdefgqwerty";
Alexey Shmalko
  • 3,678
  • 1
  • 19
  • 35
  • The runtime version of `strcpy` would also go nuts on a string literal destination. So that's why I asked the OP whether what they originally implemented is acceptable. – PaulMcKenzie Sep 06 '14 at 23:09