2017-01-30 4 views
0

親ストリングに十分なメモリを割り当て、すべてのヌルをチェックし、最後に親ストリングを '\ 0'で終了しました。2つの文字列を連結する際にセグメンテーションフォルトが発生する

セグメンテーションフォールトは、この行にあります:
私は間違っているつもりです *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);' 'のchar * FIRST_NAMEと= malloc(sizeof(char)* 20); 'または' char * first_name = malloc(20); ' –

答えて

2

次の2行を詳しく見てみましょう:最初の文字に20のポインタのための十分なメモリを割り当て、そのメモリにfirst_nameポイントを作る

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

を。

2行目は、別の場所を指すようにfirst_nameを変更して、割り当てた元のメモリを失い、メモリリークを引き起こします。 first_nameは、読み取り専用の固定サイズの5文字(文字列"ani\0"と通常の文字列ターミネータの)を指しているため、このポインタを文字列連結の宛先として使用しようとすると、 未定義の動作

これは非常に効果的です。

int some_value = 5; 
some_value = 10; 

、次いでsome_value5に等しくない理由を疑問。

溶液代わりfirst_nameコピーに文字列である:

​​
関連する問題