Solved

segmentation error problem with my stack class

Posted on 2004-10-18
6
377 Views
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
{
 public:

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

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

  //destructor
       ~stack();

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

 private:

       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]);
      i=i+1;
  }

  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!
}


stack::~stack(){

  delete []stackptr;
  delete stackptr;


}

// temporary helper functions

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




/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Driver/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#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++){
  mystack.push(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,

-TH
0
Comment
Question by:travishaberman
6 Comments
 
LVL 22

Expert Comment

by:cookre
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?
0
 

Author Comment

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

-TH
0
 

Author Comment

by:travishaberman
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.

-TH
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 

Author Comment

by:travishaberman
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?

-Th
0
 
LVL 3

Expert Comment

by:hweber
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.
0
 
LVL 1

Accepted Solution

by:
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!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

A short article about problems I had with the new location API and permissions in Marshmallow
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
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…

707 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now