Question

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?

Was it helpful?

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.

OTHER TIPS

you malloc sentences and return it to the caller. Do you free it there?

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:

strToken = malloc((strlen(str)+1)*sizeof(char));
memset(strToken,0,strlen(str)+1);

You shouldn't malloc string which is used to hold return value of strtok. Check the reference for strtok. Hence the memleak.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top