2017-01-30 45 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代替:

​​