I have the following code for creation of a node inside a graph. I'm getting resource leak error when I run a static checking tool (coverity). I would appreciate if you can point out how to improve the code:
class node {
public :
explicit node(std::string& name) : m_name(name) { }
void setlevel(int level)
{ m_level = level; }
private :
...
}
class graph {
public :
void populateGraph()
{
std::string nodeName = getNodeName();
/* I get error saying variable from new not freed or pointed-to in function
nc::node::node(const std::string...) */
node* NodePtr = new node(nodeName);
/* I get error saying variable NodePtr not freed or pointed-to in function
nc::node::setLevel(int) */
NodePtr->setLevel(-1);
if (m_name2NodeMap.find(nodeName) == m_name2NodeMap.end())
m_name2NodeMap[nodeName] = NodePtr;
NodePtr = NULL;
}
....
private :
std::map< std::string, node*> m_name2NodeMap;
}
I thought I needed to delete NodePtr
in populateGraph
, but then released it will call node desctructor (~node
) and delete the node from the graph. So, I set NodePtr=NULL
to see if it helps, but it is not.
new
does not require adelete
. Everynew
result shall be stashed in a resource manager (smart pointer or whatever) that would dispose of the memory when it is called for. Trying to do it manually is akin to juggling with fire torches in a gun powder barrel. – Kinsonunique_ptr
, ascoped_ptr
or aauto_ptr
are far from being overkill. They are simple, they work well, and unlike hand-written code, they don't screw up.delete
is a code smell (or "code omen", a warning of impeding doom). RAII is the only reliable solution, and anyone choosing an unreliable solution is either malign or ignorant. I hope the latter can be fought off. – Kinson