Search code examples
c++memory-managementmemory-leakstrie

Is this geeksforgeeks trie implementation having a memory leak problem?


I am reading a geeksforgeeks_implementation_of_trie, and i find that the TrieNode objects that are created by new are undeleted, in the main function, there is an undeleted pointer root:

struct TrieNode *root = getNode(); 

and in function getNode() there is also undeleted pointer pNode, is there any memory leak? Is there should be a function that is responsible for the destruction of the trie tree composed by pointers?

struct TrieNode *getNode(void) 
{ 
    struct TrieNode *pNode =  new TrieNode; 
    pNode->isEndOfWord = false; 
  
    for (int i = 0; i < ALPHABET_SIZE; i++) 
        pNode->children[i] = NULL; 
  
    return pNode; 
} 

Solution

  • This function implies a contract where the caller of the function is responsible for deleting the allocated TrieNode. There's only a memory leak if the caller does not honor this contract.

    Since you said this TrieNode is not deleted anywhere in main, there is likely a leak. Unless you can find somewhere this struct is deleted, there's a leak. This is why RAII is such a powerful concept. If there was a Trie object that contained all the TrieNodes and was responsible for node allocation and deletion, then you wouldn't have to worry about leaks at all.

    Making the caller responsible for managing allocated resources is dangerous. Don't do it.

    You can argue that this particular implementation isn't necessarily a leak, if the program is simple enough that all it does is acquire the TrieNodes, do things with them, and then exit. In that case the memory will be released to the OS on the program exiting anyway. But this is a semantic argument, and providing example code that does this is bad practice, and can lead to cargo cult programmers doing that bad practice.