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을 두 번 사용하기 때문에 메모리 누수가 발생합니까? 여기에 내 질문은 단어를 쓰고있을 때 ** 단어에 대한 메모리를 이미 할당하고 있기 때문입니다. [word_being_allocated] = (char *) malloc (size); 그것은 다시 할당하지 않습니다.이 컨텍스트에서 malloc을 사용하면 메모리 누수가 발생합니까?
당신은 어떤 언어로 쓰고 있습니까? C++ 또는 C? –
왜 [malloc()의 결과를 캐스팅합니까] (http://stackoverflow.com/q/605845/296974)? – glglgl
이것은 실제 코드가 아니거나 [MCVE]가 아닙니다. 예 : 'while' 또는'if'를 닫지 마십시오 .... –