So I've been following a tutorial for making a stack in C++ (here), and I believe I copied his code line for line, but I keep getting this unhandled exception error. I was thinking it had something to do with a pointer, but after scouring my program I can't identify any pointer that is being accessed inappropriately. The exact error message is: "Unhandled exception at 0x00D45446 in Project50.exe: 0xC0000005: Access violation reading location 0x00000014." The program output's the 4th Push, but none of the previous three (what appears on screen, except that the spaces should be dashed lines, but this causes the post to format to bold):
name: Water value: 3
Popping
name:
I'm using visual studio 2012, and the person doing the tutorial is using the Netbeans IDE. Is it possible this is a permissions problem?
Header file:
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
class Stack {
private:
struct item {
string name;
int value;
item* prev;
};
item* stackPtr;
public:
void Push(string name, int value);
void Pop();
void ReadItem(item* r);
void Print();
Stack();
~Stack();
};
Stack implementation:
#include "Header.h"
using namespace std;
Stack::Stack() {
stackPtr = NULL;
}
Stack::~Stack() {
item* p1;
item* p2;
p1 = stackPtr;
while( p1 != NULL) {
p2 = p1;
p1 ->prev;
p2->prev = NULL; // Not actually necessary, but distinguishes that p1 and p2 are pointing to different things
delete p2;
}
}
void Stack::Push(string name, int value) {
item* n = new item;
n->name = name;
n->value = value;
if(stackPtr = NULL) { // For first item of the stack
stackPtr = n;
stackPtr->prev = NULL; // So that the item at the bottom of the stack points to null
}
else {
n->prev = stackPtr;
stackPtr = n;
}
}
void Stack::ReadItem(item* r) {
cout << "-------------------------\n";
cout << "name: " << r->name << endl;
cout << "value: " << r->value << endl;
cout << "-------------------------\n";
}
void Stack::Pop() {
if(stackPtr = NULL) {
cout << "There is nothing on the stack\n";
}
else {
item* p = stackPtr;
ReadItem(p);
stackPtr = stackPtr->prev;
p->prev = NULL; // Again, like the one in the destructor, not actually necessary.
delete p;
}
}
void Stack::Print() {
item* p = stackPtr;
while(p != NULL) {
ReadItem(p);
p = p->prev;
}
}
Main:
#include "Header.h"
using namespace std;
int main(int argc, char** argv) {
Stack Dan;
Dan.Push("Dan", 3);
Dan.Push("Coffee", 1);
Dan.Push("Donuts", 0);
Dan.Push("Water", 3);
Dan.Print();
cout<< "Popping\n";
Dan.Pop();
cout<< "Popping\n";
Dan.Pop();
cout<< "Popping\n";
Dan.Pop();
cout<< "Popping\n";
Dan.Pop();
cout<< "Popping\n";
Dan.Pop();
cout << '\n';
system("PAUSE");
return 0;
}
using namespace std;
especially not in a header. – greatwolf