Please refer the code given here:
This code is a part of stack implementation in C++:
Code 1:
void Stack::pop()
{
if (top != 0) {
node* temp = top;
top = top -> link;
delete temp;
}
}
Code 2:
void Stack::pop()
{
if (top != 0) {
node* temp = new node;
temp = top;
top = top -> link;
delete temp;
}
}
In first example, I didn't use new, while I did use it in second one. On running, both give same output with the complete program, which can be found below:
#include <iostream>
using namespace std;
struct node {
string name;
node* link;
};
class Stack
{
node* top;
public:
Stack();
void push(string s);
void pop();
void display();
~Stack(){}
};
Stack::Stack() {
top = 0;
}
void Stack::push(string s)
{
node* temp = new node;
temp -> name = s;
temp -> link = top;
top = temp;
}
void Stack::pop() // Function in question
{
if (top != 0) {
node* temp = new node;
temp = top;
top = top -> link;
delete temp;
}
}
void Stack::display()
{
node* temp = new node;
temp = top;
while (temp != 0)
{
cout << temp -> name << "\n";
temp = temp -> link;
}
}
int main() {
Stack s;
s.push("Ra");
s.push("Sa");
s.push("Ga");
s.pop();
s.display();
}
What is the difference in using and not using new pointer here?
Also does the memory automatically free itself or do I have to do it in destructor? If so, how to do it?
There's memory leak in the 2nd code snippet, even though it looks working well. new node is meaningless for node* temp = new node;, because temp is assigned to top at once. Then the original memory address created by new node is lost and couldn't be deleted again.
Also does the memory automatically free itself or do I have to do it in destructor?
Each object newed has to be deleted by yourself. Consider about smart pointers, they will manage such things for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With