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?
Here's a memory leak:
strToken = malloc((strlen(str)+1)*sizeof(char));
// ...
strToken = strtok(str, SENTENCE_DELIMITERS);
You allocate space for an object with malloc, then lose the pointer to that space after calling strtok.
you malloc sentences and return it to the caller. Do you free it there?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With