2010-08-05 39 views
4

我試圖將一個字符串拆分成句子(由句子分隔符分隔)。代碼本身工作,但我不斷收到內存泄漏的功能。與strtok分隔句子時的內存泄漏

char ** splitSentences(char *string) { 

int sentencecount = 0; 
char* buf = NULL; 
char* str = NULL; 

buf = malloc((strlen(string) + 1) * sizeof(char)); 
strcpy(buf,string); 

str = buf; 

sentencecount = countSentences(str); 

if(sentencecount != 0) 
{ 
    char** sentences = NULL; 
    sentences = malloc((sentencecount + 1)*sizeof(char*)); 
    memset(sentences,0,sentencecount+1); 

    char* strToken = NULL; 
    strToken = malloc((strlen(str)+1)*sizeof(char)); 
    memset(strToken,0,strlen(str)+1); 

    strToken = strtok(str, SENTENCE_DELIMITERS); 

    int i = 0; 

    while(strToken != NULL) { 
     sentences[i] = NULL; 
     sentences[i] = malloc((strlen(strToken)+1)*sizeof(char)); 
     strncpy(sentences[i], strToken,strlen(strToken) + 1); 
     strToken = strtok(NULL, SENTENCE_DELIMITERS); 
     i++; 
    } 

    sentences[sentencecount] = NULL; 

    //Free the memory 
    free(strToken); 
    strToken = NULL; 

    free(buf); 
    buf = NULL; 

    return sentences; 
} 

return NULL; 

}

我找不到爲什麼會出現內存泄漏。有人知道嗎?

+0

您還可以將所有'malloc/memset'組合組合到'calloc'調用中,這將使您的代碼更易於捕捉。 – 2010-08-05 15:10:16

+1

您可以調用malloc()四次並釋放()兩次。你必須釋放()你的malloc()。 – Dingo 2010-08-05 15:11:04

回答

9

這裏有內存泄漏:

strToken = malloc((strlen(str)+1)*sizeof(char)); 
// ... 
strToken = strtok(str, SENTENCE_DELIMITERS); 

您與malloc對象分配空間,然後失去了指針,空間調用strtok後。

+0

它的工作原理!非常感謝! – Moox 2010-08-05 15:39:29

1

malloc句子和return它給調用者。你有空嗎?

1

strtok()返回指向該字符串中找到的標記的指針。在你的例子中,我不相信你需要分配strToken變量(它只是一個指針)。嘗試刪除:

strToken = malloc((strlen(str)+1)*sizeof(char)); 
memset(strToken,0,strlen(str)+1); 
0

您不應該用於保存strtok返回值的malloc字符串。 檢查參考文獻strtok。因此,memleak。