need Help with "assertion Failed"
Oct 7, 2013 at 7:44am UTC
hi!
line:39 When I uncomment delete statement my program gives "debug assertion failed" only when using <string> type;
line:91 is not usually required but it also does the same;
Any help will be much appreciated;
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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
//*************ArrStack.h******************
#include <iostream>
#include <string>
#pragma once
using namespace std;
template <class T>
class ArrStack
{
enum { DEF_CAP = 100 };
private :
T *arr;
int max, t;
public :
ArrStack(int cap = DEF_CAP);
~ArrStack(void );
bool empty(void );
void push(T e);
void pop(void );
T top(void );
int size(void );
bool full(void );
void maxPlus(void );
void print(void );
};
template <class T>
ArrStack<T>::ArrStack(int cap)
{
max = cap;
arr = new T[max];
t = -1;
}
template <class T>
ArrStack<T>::~ArrStack(void )
{
//delete arr;
}
template <class T>
bool ArrStack<T>::empty(void )
{
return t == -1;
}
template <class T>
void ArrStack<T>::push(T e)
{
if (full())
maxPlus();
arr[++t] = e;
}
template <class T>
void ArrStack<T>::pop(void )
{
if (!empty())
t--;
}
template <class T>
T ArrStack<T>::top(void )
{
if (!empty())
return arr[t];
}
template <class T>
int ArrStack<T>::size(void )
{
return (t + 1);
}
template <class T>
bool ArrStack<T>::full(void )
{
return size() == max;
}
template <class T>
void ArrStack<T>::maxPlus(void )
{
T *temp = new T[max];
temp = arr;
max += 10;
arr = new T[max];
for (int i = 0 ; i < size(); i++)
arr[i] = temp[i];
//delete temp;
}
template <class T>
void ArrStack<T>::print(void )
{
if (empty())
return ;
cout << "(" ;
for (int i = 0; i <= t; i++)
cout << arr[i] << ", " ;
cout << "\b\b)" << endl;
}
1 2 3 4 5 6 7 8 9 10 11
// ***************main*****************
#include "ArrStack.h"
int main(void )
{
ArrStack <string> obj;
obj.push("a string" );
obj.push("is being printed" );
obj.print();
return 0;
}
line:64 please guide me, What should top() return when stack is empty?? How an Exception is thrown?
Last edited on Oct 7, 2013 at 7:48am UTC
Oct 7, 2013 at 8:02am UTC
You should use
delete[] arr; when dealing with arrays.
top() should probably either throw an exception or have an unspecified behavior.
1 2 3
#include <stdexcept>
//...
throw std::out_of_range("stack is empty" );
Last edited on Oct 7, 2013 at 8:02am UTC
Oct 7, 2013 at 8:37am UTC
Thank you MiiNiPaa
Problem Solved :)
Topic archived. No new replies allowed.