Stack implementation Problem

Hi all,
This is my first time posting here and I am seriously hoping you guys could help me. I am doing this implementation of a stack class and for the life of me I cant get the copy constructor to work properly. It keeps returning invalid allocation size, but there are no negative numbers involved in anything here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<iostream>
using namespace std;
//sizes is an int, top is an int, and stackt is an int pointer
stack::stack(int sizes){
	cout<<sizes;
	stackt = new int[sizes];
	top=-1;
}
stack::stack(const stack &copy)
	:sizes(copy.sizes), top(copy.top)
{
	cout<<copy.top;
	stackt = new int[sizes];
	for (int i=0; i<sizes; i++)
		stackt[i]=copy.stackt[i];
	top=copy.top;
}
stack::~stack(){
	delete [] stackt;
}
int stack::stackpop(){
	if(isEmpty()) 
		cout<<"stack underflow";
	else
		return(stackt[top--]);
}
void stack::stackpush(int ring){
	if (isFull())
		cout<<"stack overflow";
	else
		stackt[++top]=ring;
}
int stack::stackview() {
	if (isEmpty())
		return 0;
	else
		return(stackt[top]);
}
bool stack::isEmpty(){
	return(top<0);
}
bool stack::isFull(){
	return(top==sizes);
}
try posting the code you're trying to run too. There could be a simple hidden mistake in your main.cpp

EDIT: from what i see, your sizes variable has no use in the program. Your initial constructor never sets sizes to the int passed. Your sizes variable is just full of garbage at the moment because nothing was assigned to it.

1
2
stack::stack(const stack &copy)
	:sizes(copy.sizes), top(copy.top)


sizes is never defined or set, leaving a variable with garbage in it.
Last edited on
I already found the problem thanks alot ^^. Basically i used sizes as a variable in the private part and as the name of the arguement. Caused it to randomnly spaz and give garbage as the value. Fixed it by changing the arguement name to sizes 2 and assigning its value to sizes. Btw that green comment was supposed to be the variables i defined in the private part. Just for my info can I mark this question as answered or something?
yes, once your question is answered just mark it as solved. It helps keep the forum flowing smoothly.
Topic archived. No new replies allowed.