2013-04-15 26 views
0

指向泄漏內存的函數的鏈接。我如何在這裏泄漏記憶,我每次分配記憶時都會釋放臨時記憶我不是嗎?

bool check(const char* word) 
{ 

    uint32_t len = strlen(word); 
    char currentWord[len+1]; 

    for(int k = 0; k <= len; k++) 
    { 
     currentWord[k] = tolower((char)word[k]); 
    } 

    bool wordPresent = false; 
    uint32_t indexSize = (dict.wordCount/ITEMSPERBUCKET); 
    uint32_t index = (hashFunction(currentWord)%(indexSize-1)); 

    dictNode *temp = malloc(sizeof(dictNode)); 
    temp = chainedHashTable[index]; 
    do 
    { 
     if (strncmp(temp->word, currentWord, temp->len) == 0) 
     { 
      wordPresent = true; 
      temp = NULL; 
     } 
     else 
     { 
      temp = temp->next; 
     } 
    } 
    while (temp != NULL); 

    free(temp); 
    return wordPresent; 
} 

http://codepad.org/G8uuS79s

任何幫助將不勝感激。

回答

4

在分配它之後,您會在下一行失去malloc'd的temp的值......在此之後,您還沒有得到free()的值。

此外,當您最終退出while循環並且在撥打free()之前,temp == NULL。

+0

謝謝你的真棒快速反應,儘快找到解決方案! –

4

後直接您malloc

dictNode *temp = malloc(sizeof(dictNode)); 
temp = chainedHashTable[index]; 

chainedHashTable[index]覆蓋malloc版內存的地址。因此你失去了唯一的處理malloc ed內存,並泄漏。

幸運的是,你正在釋放

while (temp != NULL); 

free(temp); 

是一個空指針,並free ING是無害的。例如,如果您嘗試使用freechainedHashTable[index],那可能會破壞您的程序。

+0

謝謝你的快速反應,只要我閱讀你的解決方案,就會有魅力和facepalm! –