Upon running this test file, I'm getting this output:
#include <iostream>
#include <string>
#include "Stack.h"
using namespace std;
int main()
{
string Text;
Stack S1;
S1.push("Mary");
S1.push("Apple");
S1.push("Tom");
S1.peek(Text);
cout << "Results from peek: " << Text << endl;
S1.view();
cout << "Hello";
Stack S2(S1);
}
Results from peek: Tom
TOP -> Tom -> Apple -> Mary -> BOTTOM
Segmentation fault
After some probing around, I believe the cause of this error to be in the destructor(?). Running GDB, it outputs this:
Program received signal SIGSEGV, Segmentation fault.
__GI___libc_free (mem=0x55fa1e0ff3c3c990) at malloc.c:3102
3102 malloc.c: No such file or directory.
That means very little to me, could anyone make a little more sense of it? Thank you.
Edit: Using Valgrind, it outputs a very long line of code, which also doesn't make sense, but does confirm that the destructor is what is making the program unhappy. The first two errors are shown below.
==1236== Conditional jump or move depends on uninitialised value(s)
==1236== at 0x10983D: Stack::~Stack() (in my_folder)
==1236== by 0x1094D1: main (in my_folder)
==1236==
==1236== Use of uninitialised value of size 8
==1236== at 0x109846: Stack::~Stack() (in my_folder)
==1236== by 0x1094D1: main (in my_folder)
==1236==
My class is defined as follows:
typedef std::string SElement;
class Stack {
public:
Stack();
Stack( Stack & );
~Stack();
void push ( const SElement );
void pop( SElement & );
void peek( SElement & );
void view();
private:
struct SNode;
typedef SNode * SNodePtr;
struct SNode {
SElement element;
SNodePtr next;
};
SNodePtr top;
};
Just in case, here's the other functions used:
void Stack::pop ( SElement &Text)
{
if(top == nullptr) {
cout << "The stack is empty. No StackElement has been removed." << endl;
}
else {
SNodePtr SecondInLine = top->next;
Text = top->element;
delete top;
top = SecondInLine;
}
}
void Stack::push( const SElement Text)
{
SNodePtr NewNode = new SNode;
NewNode->next = top;
NewNode->element = Text;
top = NewNode;
}
Edit: added Default Constructor and Destructor.
Stack::Stack()
{
top = nullptr;
}
Stack::~Stack()
{
SNodePtr nextNode;
while (top != nullptr) {
nextNode = top->next;
delete top;
top = nextNode;
}
}