[英]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.