简体   繁体   中英

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;
}

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() .

The %s specifier is for strings, eg, a char* referring to the first character of a string.

When you pass dest[i][20] to the printf function, it is not a char* . It is a single char , the 21st char (valid indices are 0 - 19 , for a total of 20 elements).

So it is an array-out-of-bounds-index, and also, not a char* as printf expects.

printf("%s\n", dest[i][20]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM