用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;
。
我找不到它泄漏内存的原因 有谁知道吗?
I'm trying to split a string into sentences (delimited by sentence delimiters). The code itself it working but I keep getting memory leaks in the function.
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;
}
I can't find why it leaks memory. Does anyone know?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个内存泄漏:
您使用
malloc
为对象分配空间,然后在调用strtok
后丢失指向该空间的指针。Here's a memory leak:
You allocate space for an object with
malloc
, then lose the pointer to that space after callingstrtok
.你
malloc
语句并将其返回
给调用者。你在那里释放它吗?you
malloc
sentences andreturn
it to the caller. Do you free it there?strtok()
返回指向字符串中找到的标记的指针。在您的示例中,我认为您不需要分配 strToken 变量(它只是一个指针)。尝试删除:strtok()
returns a pointer to the token found in the string. In your example, I don't believe you need to allocate the strToken variable (it's just a pointer). Try removing:您不应该 malloc 用于保存 strtok 返回值的字符串。
检查 strtok 的参考。因此出现了memleak。
You shouldn't malloc string which is used to hold return value of strtok.
Check the reference for strtok. Hence the memleak.