memory leaks!

i keep getting memory leaks and i tried several method from google on how to avoid it but it still there.

anyone knows how to fix this?

h file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

class Stack
{
     private:

             struct node
         {
	     std::string data;
	     node *next;
         };
			 node * start;

   public:

         Stack();
         void push(std::string n);
         std::string pop();
         unsigned long count();
         ~Stack();
};



cpp file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

#include <string.h>
#include <iostream>
#include "stack.h"

using namespace std;

Stack::Stack()
{
     start =NULL;
}

void Stack::push(std::string n)
{
   node *ptr,*ptr2;

   ptr = new node;
   ptr->data = n;
   if( start == NULL )
   {      
      ptr->next = NULL;
	  start = ptr;
   }
   else
   {
      ptr2 = start;
	  while( ptr2->next != NULL ){
		  ptr2 = ptr2->next; }
      ptr2->next = ptr;
   }

}

std::string Stack::pop()
{
     node *ptr,*ptr2;
	 
	 if (start != NULL){
		 ptr = start;
		 if (ptr->next == NULL){
			 return ptr-> data;
			 delete ptr;
			 start = NULL;
		 }
		 else{		 			 
			 while (ptr->next != NULL){
				 ptr2 = ptr;
				 ptr = ptr->next;}

			 return ptr-> data;
			 delete ptr;
			 ptr2->next = NULL;
                 }
		 
	 }
	 else{
              return "";}

	 
		 
}


unsigned long Stack::count()
{
   node *ptr;
   int i = 0;

   for( ptr = start ; ptr != NULL ; ptr = ptr->next)
        i++;

   return i;
}


Stack::~Stack()
{
   node *ptr;

  while( start != NULL )
   {
      ptr = start->next;
      delete start;
      start = ptr;
   }
}





any help would be much appreciated. :D
In push, the new node's next pointer isn't set to null if the list isn't empty.

In pop, you return the value in the node before you delete the node and so the node is never actually deleted. The compiler ought to be warning you about unreachable code at this point.

Topic archived. No new replies allowed.