Search code examples
cmemory-leaksstrtok

Memory leak when splitting sentences with strtok


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?


Solution

  • 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.