none
stack around variable corrupted

    Question

  • Hi,I'm learning C++ and am a beginner.Currently I am writing console applications to learn the basics and have just begun using classes.I'm implementing a push-down stack program but using arrays not vectors as an exercise.I Keep getting 'Run-Time Check failure#2 error: stack around the variable "stack" was corrupted. Here's my code:

     

     

    //Ex7.5
    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    //A class to represent a stack
    class CStack
    {
    private:
    		
    	int m_List[10];		//array to hold int values for the stack
    
    public:
    
    //Default Constructor Definition
    CStack()
    	{
    		//Initialize all values in array to 0
    		for(int i = 0;i < sizeof m_List;i++)
    			m_List[i] = 0;
    	}
    
    	void push(int x);
    	int pop();
    	void print();
    };
    
    int main()
    {
    	//Create an object of CStack and test the class with Functions
    	CStack stack;
    	stack.push(12);
    	stack.push(20);
    
    	cout << endl << "Number " << stack.pop() << " has been popped out of the stack.";
    
    	stack.print();
    
    	cout << endl;
    	return 0;
    }
    
    //Function to push a number into the stack
    void CStack::push(int x)
    {
    //Increment positions to make 1st position available for the number passed
    	for(int i = 0;i < sizeof m_List;i++)
    		m_List[i + 1] = m_List[i]; 
    
    	m_List[0] = x;
    }
    
    //Function to remove top item from stack
    int CStack::pop()
    {
    	int value = m_List[0];		//Get top Value
    	//all elements move back one position in stack
    	for(int i = 0;i < sizeof m_List;i++)
    		m_List[i] = m_List[i + 1];
    
    	return value;
    }
    
    //Function to Print out the stack contents
    void CStack::print()
    {
    	cout << endl;
    	cout << "The stack contains: ";
    	for(int i = 0;i < sizeof m_List;i++)
    		cout << setw(2) << m_List[i];
    }
    
    

     

    Saturday, July 24, 2010 4:23 PM

Answers

  • You are assuming that the sizeof(m_List) is 10. It is not.
    • Marked as answer by Thunderhawk60 Sunday, July 25, 2010 9:31 AM
    Saturday, July 24, 2010 4:29 PM
  • > Keep getting 'Run-Time Check failure#2 error: stack around the variable "stack" was corrupted.

    Further to Brian's hint, have a look at _countof instead.

    Dave

    • Marked as answer by Thunderhawk60 Sunday, July 25, 2010 9:31 AM
    Saturday, July 24, 2010 4:49 PM

All replies

  • You are assuming that the sizeof(m_List) is 10. It is not.
    • Marked as answer by Thunderhawk60 Sunday, July 25, 2010 9:31 AM
    Saturday, July 24, 2010 4:29 PM
  • > Keep getting 'Run-Time Check failure#2 error: stack around the variable "stack" was corrupted.

    Further to Brian's hint, have a look at _countof instead.

    Dave

    • Marked as answer by Thunderhawk60 Sunday, July 25, 2010 9:31 AM
    Saturday, July 24, 2010 4:49 PM