Kemal Tezer Dilsiz
Kemal Tezer Dilsiz

Reputation: 4009

C++ Stack generic class, int variable getting 32765 as value instead of 1

The title says the most of it. My variable "full" gets the value 3276 instead of 0;

Here is my header;

#ifndef GENERICSTACK_H
#define GENERICSTACK_H

#include <iostream>

using namespace std;

template <class T> class genericStack
{
    int MaxItems;
    T* stack;

    int empty;
    int full;
    int length;

public:

    genericStack(int);
    void push(T);
    T pop();
};

#endif // GENERICSTACK_H

Here is my .cpp file

Only the constructor is important really. Because Qt debugger shows that it does not change value in the constructor. It is originally 32765 before anything.

#include "genericstack.h"

template <class T> genericStack<T>::genericStack(int size)
{
  MaxItems = size;

  stack = new T[MaxItems];

  empty = 1;
  full = 0;
}

template <class T> void genericStack<T>::push(T item)
{
  if(full == 1)
{
    cout << "The stack is full.";
  }else
{
    stack[length] = item;
    length++;
    empty = 0;
}

if(length == MaxItems)
    full = 1;

}

template <class T> T genericStack<T>::pop()
{
  T temp;

  if(empty == 1)
    {
      cout<< "The stack is already empty.";
      return NULL;
  }else
    {
      temp = stack[length];
      stack[length] = NULL;
      length--;
      full = 0;
    }

    if(length == 1)
        empty = 1;

    return temp;
}

Upvotes: 1

Views: 2321

Answers (1)

David Schwartz
David Schwartz

Reputation: 182827

Your constructor doesn't set length to zero. When you use it as an array index, you stomp on memory, corrupting data.

Upvotes: 3

Related Questions