c - 子函数内的 malloc、free 和 memmove

标签 c malloc free memmove

我想使用一个子函数来复制一个字符数组。是这样的:

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
}

这样,我就可以从主函数中调用它,并按这种方式执行操作:

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

NSV_String_Copy (MySource, MyDestination);

但是,它没有按预期工作。请帮忙!

最佳答案

C 按值传递参数,这意味着您不能使用问题中的函数原型(prototype)更改调用者的 MyDestination。以下是更新调用方的 MyDestination 副本的两种方法。

选项 a) 传递 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);
}

选项 b) 从函数返回 Destination,并将其分配给 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);
}

关于c - 子函数内的 malloc、free 和 memmove,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28618434/

相关文章:

c - 使用 sizeof () 在 ANSI C 中查找函数类型长度

C++/C : Move Directory to Another Location

c - 动态内存中的 free()

C - 自由函数崩溃

c - 此函数中缺少 free() 导致内存泄漏

ios - 将 uint8_t 和 uint16_t 转换为 NSMutableData

c - 在 Bison 出错后释放留在堆栈上的指针

c - 在 C : Writing to a dynamic memory buffer 中使用 Malloc

c - gcc: "implementation-defined"malloc(0) 是如何定义的?

python - cython中 "enumerate"等价