[英]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. 我已为父字符串分配了足够的内存,检查所有空值,并在末尾以“ \\ 0”终止父字符串。
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. 第一个为20个指向字符的指针分配足够的内存,并使first_name
指向该内存。
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). 第二行将first_name
更改为完全指向其他位置,使您失去分配的原始内存(并导致内存泄漏)。 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 . 由于您将first_name
指向一个文字字符串,该字符串是只读的且具有5个字符的固定大小(字符串"ani\\0"
加上普通的字符串终止符),因此尝试将此指针用作字符串串联的目标导致不确定的行为 。
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
. 然后想知道为什么some_value
不等于5
。
The solution is to copy the string to first_name
instead: 解决方案是将字符串复制到first_name
:
char* first_name = malloc (20);
strcpy(first_name, "ani");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.