Search code examples
cstringsegmentation-faultcharstrcpy

C -Implementing strcpy() But Segfault


I have made a strcpy() function in C, and I am copying words from one array to other not just letters, but when I run it I am getting Segmentation fault what to do?

#include <stdio.h>

void strcpy1(char *dest[], char source[])
{
    while ((*dest++ = *source++));
}

int main()
{
    char source[3][20] = { "I", "made", "this" };
    char dest[3][20];

    strcpy1(&dest, source);
    
    //printing destination array contents   
    for (int i = 0; i < 3; i++) {
        printf("%s\n", dest[i][20]);
    }

    return 0;
}

Solution

  • There are multiple problems in your code:

    • the prototype for your custom strcpy1 function should be:

      void strcpy1(char *dest[], char *source[]);
      
    • the arrays source and dest are 2D char arrays: a very different type from what strcpy1 expects, which are arrays of pointers. Change the definition to:

       char *source[4] = { "I", "made", "this" };
       char *dest[4];
      
    • you should pass the destination array as dest instead of &dest

    • the source array should have a NULL pointer terminator: it should be defined with a length of at least 4. Same for the destination array.

    • in the print loop dest[i][20] refers to a character beyond the end of the i-th string. You should just pass the string as dest[i].

    Here is a modified version:

    #include <stdio.h>
    
    void strcpy1(char *dest[], char *source[])
    {
        while ((*dest++ = *source++));
    }
    
    int main()
    {
        char *source[4] = { "I", "made", "this" };
        char *dest[4];
    
        strcpy1(dest, source);
        
        //printing destination array contents   
        for (int i = 0; dest[i]; i++) {
            printf("%s\n", dest[i]);
        }
    
        return 0;
    }
    

    Note that it is somewhat confusing to name strcpy1 a function that has very different semantics from the standard function strcpy().