连接两个字符串时出现分段错误

时间:2017-01-30 07:31:19

标签: c pointers

我已经为父字符串分配了足够的内存,检查了所有空值,并通过' \ 0'来终止父字符串。最后。

此行有分段错误:
*arg_parent = *arg_child;

我哪里错了?

#include <stdio.h>
#include <stdlib.h> // malloc

int my_strcat (char* arg_parent, char* arg_child)
{
    if (arg_parent != NULL)
    {
        // Get to the end of the parent string.
        while (*arg_parent != '\0')
            arg_parent++;

        // Concatinate child string to the end of the parent string, byte by byte
        // till the child string ends.
        while (*arg_child != '\0')
        {
            *arg_parent = *arg_child;
            arg_parent++;
            arg_child++;
        }

        // Append '\0' at the end of the parent string which now has the child string
        // joined to it.
        *arg_parent = '\0';
        return 0;
    }
    else
        return -1;
}

int main ()
{
    printf ("\nsdfsdf\n");
    char* first_name = malloc (sizeof (char*) * 20);
    first_name = "ani\0";

    char last_name[4] = {'s', 'h', 'a', '\0'};

    int return_value = my_strcat (first_name, last_name);

    if (return_value == 0)
        printf ("\nfirst_name: %s\n", first_name);
    else
        printf ("\nmmmmmmmmmmmm\n");

    return 0;
}

1 个答案:

答案 0 :(得分:2)

让我们仔细看看这两行:

char* first_name = malloc (sizeof (char*) * 20);
first_name = "ani\0";

第一个为内容分配足够20个指针的内存,并使first_name指向该内存。

第二行将first_name更改为完全指向其他位置,使您丢失所分配的原始内存(并导致内存泄漏)。由于您使first_name指向一个只读且具有固定大小为5个字符的字符串(字符串"ani\0" 加上正常字符串终止符),尝试使用此指针作为字符串连接的目标将导致未定义的行为

这非常像是在做。

int some_value = 5;
some_value = 10;

然后想知道为什么some_value不等于5

解决方案是将复制字符串改为first_name

char* first_name = malloc (20);
strcpy(first_name, "ani");
相关问题