2017-03-07 5 views
0

これまでは、文字列の長さが未知の文字列(改行が発生するまで文字を読み込む)のためにこの関数を割り当てようとしました。文字列の改行までの動的メモリ割り当て関数

私の質問は、私の文字列(sという名前の)の解放に割り当てられたメモリについてです。 私は無料でこれをやろうとしました。問題は、私はどこに書くべきか分かりません。

"return s"の前の関数に書き込むと、未割り当てのポインタが返されます。

"return s"の後に関数に書き込むと、効果があるとは思いませんか? sがmain()で返されたので、決して解放されません。

このような状況について、どうすればよいですか?

これは私が得たものである:

#include <stdlib.h> 
#include <stdio.h> 

//Returns dynamic allocated string(read until the '\n' aka. newline character) 
char* input_string_line() 
{ char *s,*aux,c;      //*s(string pointer),*aux(auxiliary string pointer),c(the characters that are read) 
    int len;       //len(actual length of the string) 
    s=malloc(sizeof(char));    //firstly, allocation memory for 1 byte(8 bites), for the null character 
    if (!s)        //verification if the memory can be allocated, if not possible then the program exits 
    { printf("ERROR: Memory allocation failure (string).\n"); 
     exit(EXIT_FAILURE); } 
    s[0] = 0;       //NULL character for string ending 
    len = 0;       //the length of the string at the beginning is 0(without considering the NULL character at the end) 
    while ((c = getchar()) != '\n')  //reading character by character until newline 
    { aux = realloc(s, len + 2);  //reallocation memory for the next read character in a new auxiliary string(same as the old string, this time having memory for a new character to be added) 
     if (!aux)      //verification if the reallocation can succed: if not possible then the program exits 
     { free(s); 
      printf("ERROR: Memory allocation failure (auxiliary string).\n"); 
      exit(EXIT_FAILURE); } 
     else s = aux;     //if succeded, then the string becomes the auxiliary string 
     s[len] = c;      //the character with the [len] index will be assigned the value of the read character 
     s[len+1] = 0;     //NULL character for string ending 
     len++; }      //length increments by one each time a new character is added to the string 
    return s; 
    free(s);       
} 

int main() 
{ printf("%s",input_string_line()); 
return 0;} 

答えて

0

自然やごinput_string_line()関数を考慮すると、あなたのポインタを解放する必要がある唯一の場所は、main関数です。他の場所はポインタを生成し無効にするか、メモリリークを引き起こします。

int main() 
{ 
    char* s = input_string_line(); 
    printf("%s",s); 
    free(s); 
    return 0; 
} 
+0

よろしくお願いします。 –

+0

私がしたように文字列を印刷するとどうなりますか?私はまだ私のポインタを解放する必要がありますか? case: 'printf("%s "、input_string_line());' –

+0

はい、それを解放する必要があります。 C/C++にはガベージコレクタがありません。あなたが割り当てたものは自由にすべきです。そうしないと、メモリリークが発生します。 – Luci

関連する問題