strcpy using pointers

前端 未结 7 1116
无人及你
无人及你 2021-01-13 11:29

I\'m trying to write strcpy on my own using pointers and I get an error during runtime.

void str_cpy(char **destination, const char *source) {
//    char *s1         


        
7条回答
  •  春和景丽
    2021-01-13 12:15

    You should likely allocate some memory for that pointer before passing it off to a function that fills what it points to (which in this case, is NULL).

    Example:

    char *str = malloc(128);
    if (str)
    {
       str_cpy(&str, "String");
       free(str);
       str = NULL;
    }
    

    I advise not doing this without also providing target-buffer size information (i.e. if you're writing your own, then boundary-check the target buffer, otherwise your version has the same security flaws as strcpy() which are bad enough as it is).

    Note: Unless you're planning on changing the address held by the pointer passed as the target, you need not use a double pointer either. The double pointer usage you have prevents the traditional strcpy() usage pattern of:

    char str[128];
    str_cpy(&str, "Hello"); // error. 
    

    An array address cannot be passed as a pointer-to-pointer, so your code cannot fill a static array without an intermediate pointer:

    char str[128];
    char *p = str;
    str_cpy(&p, "Hello");  //ok. passing address of pointer.
    

    If this is not intentional (and I don't see why it could be unless you have ideas of internally emulating strdup() on a NULL pointer passage) You should address this.

提交回复
热议问题