2016-10-07 4 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을 두 번 사용하기 때문에 메모리 누수가 발생합니까? 여기에 내 질문은 단어를 쓰고있을 때 ** 단어에 대한 메모리를 이미 할당하고 있기 때문입니다. [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

malloc()과 함께 할당하는 모든 단일 메모리 블록이 올바르게 free() 개까지 메모리 누수가 발생하지 않습니다. 이 코드에서

편집 :

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); 

당신은 당신이 words 배열의 같은 포인터 슬롯을 덮어 쓸 수 있도록, word_being_allocated를 업데이트하는 것,이 경우하지 않습니다 메모리 누출 (이전에 할당 된 포인터 free). 제대로 word_being_allocated를 업데이트 할 때

는 확인을 하지 오버 플로우 words 포인터 배열의 범위합니다.

+0

문자 ** 단어 = (문자 **) malloc에 ​​(NUM_WORDS *를 sizeof (숯불 *)); 단어는 [word_being_allocated] = (숯불 *) malloc에 ​​(크기) 나는 코드의이 부분에 대한 걱정이다. – Phaneeth

+0

부분 코드를 업데이트했습니다. 너 좀 봐 주시면 고맙겠습니다. – Phaneeth

관련 문제