• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 401
  • Last Modified:

segmentation error problem with my stack class

Hello experts,

I have created a stack class and a driver to test it with.  I am getting a segmentation error for some reason.  I think that the error is happening in my resize() function.  Because the error only happens when a stack has more than 50 integers pushed onto it.  

My question is.. What is a segmentation error?  And how do I get rid of it?

Below is my stack class definition, stack class implementation, and driver.

Stack Class Definition

#include <cstdlib>
#include <string>

using namespace std;

#ifndef STACK_H
#define STACK_H

class stack

 //default constructor
       stack(int size=50);

  //member functioins
       stack copy();
       bool push(const int& d);
       int pop();
       bool isempty() const;
       bool isfull() const;


  //temporary helperfunctions
       int returntop();
       int returnmax();


       int *stackptr;   // need to declare a pointer to an array
       int max;         //declare max to keep track of array capacity
       int top;         //declare top to keep track of last item put on stack
       bool resize();   //helper function to resize stack to fit more data

Stack Class implementation/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#include "stack.h"
#include <iostream>
#include <cstdlib>

using namespace std;

//default constructor
stack::stack(int size){

  stackptr = new int[size];
  top = -1;
  max = size;

//copy constructor
stack stack::copy(){

  //Note: need to preform memmory check here

  stack copycat(max);
  copycat.top = top;

  //push all values from old stack to new stack
  int i = 0;  // instanciate a counter set to zero
  while (((stackptr[i]) != NULL) && (i<= max)){ // while there is more data and we havent run to the end of our array
     (copycat.stackptr[i]) = (stackptr[i]);

  return copycat;    //  push data from incoming stack onto new  stack

//push member function
bool stack::push(const int& d){

  if(isfull() == true){  //attempt to make new bigger stack
    if(resize() == false) {return false;} // test wheter or not stack was actually created due to space
  }                                              // return false if it was not create

  //else stack was created
  top = top + 1; //increase top of stack
  stackptr[top] = d; //top will be at next open spot of array so add data at top
  return true;  // return success!

//pop member function
int stack::pop(){

  if(isempty() == true) {return NULL;} //if stack is empty return null to indicate no value
  else{                               //else
    int temp = (stackptr[top]);      //instanciate temp value and assign the value at top of array
    stackptr[top] = NULL;          //return the value at top to null
    top = top - 1;                    //decrement top by 1
    return temp;                      //return the temp value to user

//isempty member function
bool stack::isempty() const{

  if(top == -1) {return true;}  // if top is at postion -1 then no values are in array
  else {return false;}          // else top is not at -1 and there are values in array

//isfull member function
bool stack::isfull() const{

  if(top == max) {return true;} // if top is at max capacity of array then array is full
  else {return false;}          // else top is not at capicty and so array is not full

//resize helper function
bool stack::resize(){

  int *tempptr;
  int newmax = max*2;
  tempptr = new int[newmax];  //declare a new temporary pointer and point it at a new array 1.5 times as big as original

  //copy all the data from smaller array to new bigger array using for loop
  for(int i=0;((stackptr[i] != NULL) || (i<=max)); i++){tempptr[i] = (stackptr[i]);}

  delete []stackptr;  //delete the thing that stackpointer is pointing at (old array)
  stackptr = tempptr; //repoint stack pointer to the thing that tempptr is pointer is pointing too (new bigger stack)
  delete tempptr;     // delete tempptr
  max = newmax;     // increase max by 1.5 times to match our new stack size

  return true;        // return success!


  delete []stackptr;
  delete stackptr;


// temporary helper functions

int stack::returnmax(){return max;}
int stack::returntop(){return top;}


#include "stack.cpp"
#include <string>
#include <iostream>
#include <cstdlib>

using namespace std;

int  main()

  cout << endl << endl << "   Welcome to Travis's Stack Class Program" << endl << endl;
  cout << "   You may type push and pop the stack by typing valid expressions with integer arguemtns" << endl << endl << endl << endl;
  cout << "   For example, if you want to 'push' the number 3, type 'push(3)'" << endl;
  cout << "   Or, if you want to pop a value type 'pop()'" << endl;
  cout << endl << endl;
  cout << "   Type 'exit' when finished" << endl << endl;

 stack mystack;

 for (int i=0; i <= 60;i++){
  cout << endl << mystack.returnmax() <<  " " << mystack.returntop() << endl; // <<  mystack.pop() <<  endl;

 for (int i=0; i<= 60; i++){
   cout <<  mystack.pop() << endl;
   // cout << endl << mystack.returntop() << endl;

 int stuff;
  cin >> stuff;

  return 0;
}//end main


Thank you,

1 Solution
A segmentation error means you tried to access some memory that wasn't allocated to you.

I'd say your resizing isn't working.  Where is 'max' declared?
travishabermanAuthor Commented:
Max is declared in the class definition under private data...

travishabermanAuthor Commented:
Oh.. and the function seems to be working because I am getting the desired output from main.  That is, if I push on 110 integers the capacity of the stack increases to 100 and then to 200 to handel the items.  The fault only comes when I go to exit the program by returning some key stroke.

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

travishabermanAuthor Commented:
When I look at all the values in resize() the only ones that were not declared in its scope are stackptr and max.  But they are members of the private data and so I should have access to them as this is a private function in the class.  Right?

I think the line

delete tempptr;     // delete tempptr

in reserve() is unnecessary and maybe even the cause of your problem. tempptr is declared as a local variable of resize(), so it is allocated on the stack and will be cleaned up automatically when the function returns. I don't know for sure what delete does if you use it on a variable that is located on the stack, but it might do something you don't want, i. e. try to free memory it doesn't have access to.
Firstly, let me highly recommend a debugger. You could have watched the counter of your loop on the debugger and quickly understood the nature of your issue including the exact time your program crashed. This information would have given you a place to work on and a much better idea of what happened in your code.

It crashed because of the following line.

delete []stackptr;  //delete the thing that stackpointer is pointing at (old array)

Segmentation faults often happen when you either attempt to reference memory that you do not have proper access to through bad pointer arithmetic or from attempting to free memory you didn’t create.

Thus you may have noticed that you had the is_empty function wrong. If you are staring your “top” count from -1 then you need to remove that -1 from the max count. (As arrays count from zero) Overwriting the array, thus memory, and thus having nasty problems with deleting arrays.

if(top == max - 1) {return true;} // if top is at max capacity of array then array is full

And all would have progressed from there. It would have helped to have simplified the “copy” part of the expand function to something like the following.

for(int i=0;i<=top; i++){
        tempptr[i] = stackptr[i];

Remember, NULL means 0 (usually) so no point in checking integers against 0. Hope this helps. Have fun learning to program and get a debugger and learn to love it!

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now