繁体   English   中英

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

[英]Segmentation fault while concatenating two strings

我已为父字符串分配了足够的内存,检查所有空值,并在末尾以“ \\ 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;
}

让我们仔细看看这两行:

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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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