1

I am implementing a class Set, and there is member function, ironically called member, which returns true, if the value being passed is in the set, and false otherwise. My question is that, if I am creating a temporary node to iterate over to search for this value, do I need to delete this temporary node when I am done with it to return the memory to the heap, as it is not being returned from the function?

In this class, the node is embedded as a private struct in the class Set like this:

private:
  //Precondition: linked list is sorted in ascending order
  struct Node {
     int value;
     Node* link;
  };
  Node* list;
  static Node* cons(int x, Node *p);

and the function I'm referring to is:

bool Set::member(int x) const {
   if(list == nullptr) 
      return false;

   Node* tempNode = list;

   while(tempNode != nullptr) {
      if(tempNode->value > x) 
         return false;
      if(tempNode->value == x) 
         return true;
      tempNode = tempNode->link;
   }
   return false;
}
coopwatts
  • 670
  • 1
  • 8
  • 31
  • 1
    `tempNode` is not being allocated, you are pointing it to the same place `list` is pointing. – wendelbsilva Nov 20 '15 at 20:00
  • Ah right okay, I guess this follows the principle of using delete whenever using keyword new, which I did not. Thank you – coopwatts Nov 20 '15 at 20:02
  • I'm assuming your Set is for an assignment. After the assignment, if you want to know more about pointers and what exist, I suggest you to take a look into [smart pointers](http://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one). A lot of times (IMHO, most of the time) you dont have to use `new/delete` explicitly. – wendelbsilva Nov 20 '15 at 20:07
  • Duly noted, I will do that. Thanks!! – coopwatts Nov 20 '15 at 20:07
  • @wendelbsilva, well, there are plenty of cases when you have to use `new` explicitly even in the brave new world. – SergeyA Nov 20 '15 at 20:10

2 Answers2

2

No.

tempNode is just a non-static local variable with automatic storage duration; it's scope is confined to the begin and the end of the function. It is automatically deallocated when the function returns.

Community
  • 1
  • 1
cadaniluk
  • 15,027
  • 2
  • 39
  • 67
0

Your member function does not allocate any heap memory (no new or malloc calls). The tempNode variable (of size sizeof(Node*)) is going to be allocated on the stack.

When the function exits, the activation record for the whole function (containing tempNode) gets automatically deallocated, so no need to do further cleaning.

The code is correct as it is.

simpel01
  • 1,792
  • 12
  • 13
  • Wrong. Who says anything about the variable being allocated on stack? Most likely, it won't. And what is 'activation record'? – SergeyA Nov 20 '15 at 20:08