문자열을 문장으로 분리하려고합니다 (문장 구분 기호로 구분). 코드 자체는 작동하지만 함수에서 메모리 누수가 계속 발생합니다.문장을 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;
}
는 메모리 누수 이유를 찾을 수 없습니다. 아는 사람 있나요?
'malloc/memset'의 모든 조합을'calloc' 호출과 결합 할 수도 있습니다. 그러면 코드를 쉽게 캡처 할 수 있습니다. –
malloc()을 네 번 호출하고 free()를 두 번 호출합니다. 너는 무엇이든 malloc()을 자유롭게 해줘야한다. – Dingo