【发布时间】:2010-08-05 15:04:21
【问题描述】:
我正在尝试将字符串拆分为句子(由句子分隔符分隔)。代码本身可以工作,但我在函数中不断出现内存泄漏。
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;
}
我找不到它泄漏内存的原因。有人知道吗?
【问题讨论】:
-
您也可以将您的所有
malloc/memset组合组合到对calloc的调用中,这将使您的代码更容易捕获。 -
你调用 malloc() 四次和 free() 两次。你必须 free() 任何你 malloc() 的东西。
标签: c memory-leaks strtok