malloc, free, and memmove inside a subfunction

≯℡__Kan透↙ 提交于 2019-12-11 10:37:39

问题


I want to use a subfunction to copy a char array. it is like this:

void NSV_String_Copy (char *Source, char *Destination)
{
    int len = strlen(Source);
    if (*Destination != NULL)
        free(Destination);
    Destination = malloc(len + 1);
    memmove(*Destination, Source, len);
    Destination[len] = '\0';             //null terminate
}

that way, I can call it from the main function and perform the operation this way:

char *MySource = "abcd";
char *MyDestination;

NSV_String_Copy (MySource, MyDestination);

However, it does not work as intended. please help!


回答1:


C passes arguments by value, which means that you can't change the caller's MyDestination using the function prototype in the question. Here are two ways to update the caller's copy of MyDestination.

Option a) pass the address of MyDestination

void NSV_String_Copy (char *Source, char **Destination)
{
    int len = strlen(Source);
    if (*Destination != NULL)
        free(*Destination);
    *Destination = malloc(len + 1);
    memmove(*Destination, Source, len);
    (*Destination)[len] = '\0';             //null terminate
}

int main( void )
{
    char *MySource = "abcd";
    char *MyDestination = NULL;

    NSV_String_Copy(MySource, &MyDestination);
    printf("%s\n", MyDestination);
}

Option b) return Destination from the function, and assign it to MyDestination

char *NSV_String_Copy (char *Source, char *Destination)
{
    if (Destination != NULL)
        free(Destination);

    int len = strlen(Source);
    Destination = malloc(len + 1);
    memmove(Destination, Source, len);
    Destination[len] = '\0';             //null terminate

    return Destination;
}

int main( void )
{
    char *MySource = "abcd";
    char *MyDestination = NULL;

    MyDestination = NSV_String_Copy(MySource, MyDestination);
    printf("%s\n", MyDestination);
}


来源:https://stackoverflow.com/questions/28618434/malloc-free-and-memmove-inside-a-subfunction

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!