2016-10-07 2 views
-2
int num_words = 0; 
while ((c = fgetc(in_fp)) != EOF) { 
    if (c == 32 || c == 10 || c == 13 || c == 46) { 
     //32 is Space, 10 is LF, 13 is CR, 46 is period 
     //todo: Add other kinds of punctuation 
     num_words = num_words + 1; 
    } 
}         

char** words = (char**) malloc(num_words * sizeof(char*)); 
if (words == NULL) { 
    printf("Memory allocation failed\n"); 
    return 1; //abort program 
} 

//Reset the input file pointer to the start of the file 
rewind(in_fp); 

//Allocate enough space for each word 
int word_being_allocated = 0; 
int word_size = 0; 
int size; 
while ((c = fgetc(in_fp)) != EOF) { 
    if (c == 32 || c == 10 || c == 13 || c == 46) { 
     //32 is Space, 10 is LF, 13 is CR, 46 is period 
     size = (word_size + 1) * sizeof(char); 
     words[word_being_allocated] = (char*) malloc(size); 
     if (words[word_being_allocated] == NULL) { 
      printf("Memory allocation failed\n"); 
      return 1; 
     } 
     word_being_allocated = word_being_allocated + 1; 
     word_size = 0; 
     continue; 
    } 
    word_size = word_size + 1; 
} 
for (int i = 0; i < num_words; i++) { 
    free(words[i]); 
} 
free(words); 

mallocを2回使用しているので、メモリリークがありますか?ここで私の質問は、私が単語を書くときに**単語のためのメモリを割り当てているからです。[word_being_allocated] =(char *)malloc(size);それは再び割り当てられません。このコンテキストでmallocを使用するとメモリリークが発生します

+0

あなたはどの言語を書いていますか? C++またはC? –

+1

なぜあなたは[malloc() 'の結果をキャストしますか(http://stackoverflow.com/q/605845/296974)? – glglgl

+2

これはあなたの実際のコードではなく、[MCVE]でもありません。例えば'while'や' if'を閉じないでください.... –

答えて

0

私たちが見る限り、あなたが提供するコードは、malloc()メモリを捨てない限り問題ありません。だから、少なくともあなたは漏れのないチャンスがあります。あなたが本当にそうであるかどうかは、データを扱った後にどのように進むかによって異なります。

0

free()malloc()で割り当てたすべてのメモリブロックは、適切にメモリリークが発生していません。このコードで

EDIT

while ((c = fgetc(in_fp)) != EOF) { 
    if (c == 32 || c == 10 || c == 13 || c == 46) { 
     //32 is Space, 10 is LF, 13 is CR, 46 is period 
     size = (word_size + 1) * sizeof(char); 
     words[word_being_allocated] = (char*) malloc(size); 

あなたはword_being_allocatedを更新していないようですので、あなたはwords配列であり、この場合には同じポインタスロットを上書きすることがありメモリが漏れています(前に割り当てられたポインタfreeはありません)。あなたが適切word_being_allocatedを更新すると

は、確かに ないオーバーフロー wordsポインタ配列の範囲にします。

+0

char ** words =(char **)malloc(num_words * sizeof(char *)); words [word_being_allocated] =(char *)malloc(size) コードのこの部分が心配です。 – Phaneeth

+0

部分コードを更新しました。もしあなたが一見することができたら、私は感謝します。 – Phaneeth

関連する問題