//stack.cpp
#include <cstdlib>
#include <iostream>
#include "saqdef.h"
namespace saq {
TMPL
class Stack {
public:
Stack(int size = 31000): sp(0), stack(new T[size]), sz(size) {}
~Stack(void) { if(sp != 0) throw std::exception("Pushed values not popped."); }
T push(T value);
T pop(T& dest);
T pop(void);
int getsize(void);
void addmem(const int mem);
T* getstack(void);
private:
int sp, sz;
T *stack;
};
TMPL
T saq::Stack<T>::push(T value) {
stack[sp] = value;
++sp;
return value;
}
TMPL
T saq::Stack<T>::pop(T& dest) {
if(!sp || sp > MAX(sizeof(stack), 1) / sizeof(T)) {
throw std::exception("Attempting to pop a value not pushed.");
}
dest = stack[sp - 1];
--sp;
return dest;
}
TMPL
T saq::Stack<T>::pop(void) {
if(!sp || sp > MAX(sizeof(stack), 1) / sizeof(T)) {
throw std::exception("Attempting to pop a value not pushed.");
}
T ret;
ret = stack[sp - 1];
--sp;
return ret;
}
TMPL
void saq::Stack<T>::addmem(const int mem) {
T *temp;
temp = new T[sz + mem];
memcpy(&temp, &stack, sizeof(stack));
delete[] stack;
stack = new T[sz + mem];
memcpy(&stack, &temp, sizeof(temp));
sz += mem;
delete[] temp;
}
TMPL
int saq::Stack<T>::getsize(void) {
return sz;
}
TMPL
T* saq::Stack<T>::getstack(void) {
return stack;
}
}
int main() {
saq::Stack<int> myStack(2);
myStack.push(20);
myStack.push(30);
std::cout << myStack.pop() << std::endl;
std::cin.get();
myStack.pop();
}
//saqdef.h #pragma once #define TMPL template <class T> #ifndef MAX #define MAX(a, b) ((a>b)?a:b) #endif
I've checked with the debugger, and at a breakpoint on myStack.push(30)'s ++sp, stack[sp] = 30, but stack[sp] does not actually have an entry "30". It only has 20. What's going on?
I do end up with an unhandled exception:
Unhandled exception at 0x75629617 in stack_and_queue.exe: Microsoft C++ exception: std::exception at memory location 0x001bf598..It points to:
00A917C4 call @ILT+385(__RTC_CheckEsp) (0A91186h) 00A917C9 push offset [email protected]@@ (0A97D90h) 00A917CE lea ecx,[ebp-100h] 00A917D4 push ecx 00A917D5 call @ILT+290([email protected]) (0A91127h) } T ret; ret = stack[sp - 1]; 00A917DA mov eax,dword ptr [this] <--this is the next statement
EDIT: I know about the memory leak in pop().
This post has been edited by PlasticineGuy: 11 February 2010 - 02:58 AM

New Topic/Question
Reply



MultiQuote





|