Freeing memory allocated for a string in C

I have a problem with memory allocation and freeing.

I am trying to implement a dictionary using a compressed trie (Patricia). I have a trie library that works correctly when I call its functions from main. However, I have a small problem when I try to parse the input.

I have a parser library that reads a word from standard input and calls a function insert

from the trie library. He calls it this way:

void tryInsert(char *commandLine, struct tree *t) {
        char *arg[3] = { NULL };
        sscanf(commandLine, "%ms %ms%ms", &arg[0], &arg[1], &arg[2]);
        if (arg[1] == 0 || arg[2] != 0 || !consistsOfSmallCases(arg[1]))
                printf("ignored\n");
        else
                //inserting arg[1] into tree
                insert(t, arg[1]);
//      free(arg[0]);
//      free(arg[1]);
//      free(arg[2]);
}

      

Three calls to the "free" function are now marked commets because:

The function insert

has two arguments: a trie and a char *word

. Within this function I insert a suffix of word

to some of the new trie. This means that I do not want to free the memory allocated for the string at once.

However, since I am only inserting the suffix , I lose control of the prefix.

This means that if, inside a function clear

that clears the trie, I call free(node->content)

, I don't actually free all of the allocated memory.

Also, when trying and copying the string word

in char word1[256]

within the function insert

and don't comment out the ones you free, everything stops working.

I would be grateful for any ideas on how to deal with this,

+3


source to share


1 answer


You have some logical errors in your code that are always scary when dealing with dynamic memory.

The function insert()

needs to make a copy of the part of the string it wants to keep, since it only needs the prefix.



Also, you really need to check what sscanf()

succeeds before relying on variables that have valid values. If it doesn't return 3

, there was a parsing problem and not all lines were highlighted. Check the return value.

+2


source







All Articles