Implement strcpy function

Discussion in 'C' started by Dragu Mircea, Apr 18, 2018.

  1. Dragu Mircea

    Dragu Mircea New Member

    Joined:
    Apr 15, 2018
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    1
    Gender:
    Male
    Hi,
    I want to implement strcpy function, but something is go wrong.
    I have made debug and the code works until execute the function.
    I receive an error something with segmentation fault.
    Thank you.

    #include <stdio.h>
    #include <stdlib.h>

    char *strcpy(char *destination, char *source)
    {
    char *saved = destination;
    while(*source != '\0')
    {
    *destination = *source;
    destination++;
    source++;​
    }
    return saved;​
    }

    int main()
    {
    char *ptr1 = "kjshdfoiswledkj";
    char *ptr2 = NULL;
    printf("\n The value of ptr1 is : %s\n", ptr1);
    printf("\n The value of ptr2 is : %s\n", ptr2);
    strcpy(ptr2, ptr1);
    printf("\n The value of ptr1 is : %s\n", ptr1);
    printf("\n The value of ptr2 is : %s\n", ptr2);
    return 0;​
    }
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    ptr2 has never been initialized to point to any memory.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice