2017-01-30 85 views
0

我分配了足夠的內存父字符串,檢查所有的空值,並在年底通過「\ 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; 
} 
+0

要使用開始,替換'字符*如first_name = malloc的(的sizeof(字符*)* 20);'與'字符* first_name的= malloc(sizeof(char)* 20);'或'char * first_name = malloc(20);' –

回答

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代替:

​​