segmentation error problem with my stack class

Posted on 2004-10-18
Last Modified: 2012-05-05
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); = 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,

Question by:travishaberman
LVL 22

Expert Comment

ID: 12343375
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?

Author Comment

ID: 12343384
Max is declared in the class definition under private data...


Author Comment

ID: 12343409
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.

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Author Comment

ID: 12343431
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?


Expert Comment

ID: 12359878
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.

Accepted Solution

crulx earned 500 total points
ID: 12360232
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
A short article about problems I had with the new location API and permissions in Marshmallow
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

679 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question