Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 787
Moox Avatar asked Dec 23 '22 00:12

Moox


2 Answers

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.

like image 195
James McNellis Avatar answered Dec 24 '22 15:12

James McNellis


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

like image 27
Jens Gustedt Avatar answered Dec 24 '22 15:12

Jens Gustedt