Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freeing memory allocated for string in C

I'm stuck at a problem with memory allocation and freeing it.

I'm trying to implement a dictionary using a compressed trie (Patricia). I have a trie library which works correctly when I call its functions from main. However, I have a little problem when I'm trying to parse input.

I have a parser library which reads a word from the standard input and calls the insert function from the trie library. It 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]);
}

The three calls of the "free" function are now marked as commets, because:

the insert function has two argument: a trie and a char *word. Inside this function, I insert a suffix of word into some a new of the trie. This means that I don't want to free the memory that's allocated for the string right away.

However, since I'm only inserting a suffix, I lose control of the prefix.

Which means that if, inside a clear function that clears the trie, I call free(node->content), I don't actually free all the memory allocated.

Moreover, when try and copy the string word into char word1[256] inside the insert function and un-comment those thee frees, everything stops working.

I would appreciate any ideas how to deal with that,

like image 477
Jytug Avatar asked Aug 05 '26 12:08

Jytug


1 Answers

You have some logic errors in your code, which is always scary when dealing with dynamic memory.

The insert() function needs to do a copy of the part of the string that it wishes to store, since it only wants a prefix.

Also, you really should check that sscanf() succeeds before relying on the variables having valid values. If it doesn't return 3, there was a parsing problem and not all of the strings will have been allocated. Check the return value.

like image 64
unwind Avatar answered Aug 08 '26 02:08

unwind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!