简体   繁体   中英

Segmentation fault while concatenating two strings

I have allocated sufficient memory to the parent string, checked for all the nulls and terminated the parent string by '\\0' at the end.

There is segmentation fault on this line:
*arg_parent = *arg_child;

Where am I going wrong?

#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;
}

Lets take a closer look at these two lines:

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

The first allocates memory enough for 20 pointers to characters, and makes first_name point to that memory.

The second line changes first_name to point somewhere else completely, making you lose the original memory you allocated (and leading to a memory leak). Since you make first_name point to a literal string, which is read only and with a fixed size of 5 character (the string "ani\\0" plus the normal string terminator), attempting to use this pointer as the destination for a string concatenation will lead to undefined behavior .

This is very much like doing eg

int some_value = 5;
some_value = 10;

and then wondering why some_value isn't equal to 5 .

The solution is to copy the string to first_name instead:

char* first_name = malloc (20);
strcpy(first_name, "ani");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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