I am trying to implement a Dynamic Stack in c++. i have 3 members in class stack 1.cap is the capacity. 2.top- points to top of stack 3. arr- pointer to an integer.
in the class constrcutor I am allocating memory to stack(malloc). later in the meminc() I am trying to realloc the memory.
I have written a function meminc() to realloc the memory but i get this invalid old size error.
It would be helpful if you let me know what is wrong in this code. I will also appreciate any advice given to me. Thank you.
#include <iostream>
using namespace std;
#define MAXSIZE 5
class stack {
int cap;
int top;
int *arr;
public:
stack();
bool push(int x);
bool full();
bool pop();
bool empty();
bool meminc();
};
stack::stack()
{
cap = MAXSIZE;
arr = (int *)malloc(sizeof(int)*MAXSIZE);
top = -1;
}
bool stack::meminc()
{
cap = 2 * cap;
cout << cap << endl;
this->arr = (int *)realloc(arr, sizeof(int)*cap);
return(arr ? true : false);
}
bool stack::push(int x)
{
if (full())
{
bool x = meminc();
if (x)
cout << "Memory increased" << endl;
else
return false;
}
arr[top++] = x;
return true;
}
bool stack::full()
{
return(top == MAXSIZE - 1 ? true : false);
}
bool stack::pop()
{
if (empty())
return false;
else
{
top--;
return true;
}
}
bool stack::empty()
{
return(top == -1 ? true : false);
}
int main()
{
stack s;
char y = 'y';
int choice, x;
bool check;
while (y == 'y' || y == 'Y')
{
cout << " 1.push\n 2.pop\n" << endl;
cin >> choice;
switch (choice)
{
case 1: cout << "Enter data?" << endl;
cin >> x;
check = s.push(x);
cout << (check ? " push complete\n" : " push failed\n");
break;
case 2: check = s.pop();
cout << (check ? " pop complete\n" : " pop failed\n");
break;
default: cout << "ERROR";
}
}
}
To add to john's answer,
the way you're using realloc()
is ... flawed.
bool stack::meminc() { cap = 2 * cap; cout << cap << endl; this->arr = (int *)realloc(arr, sizeof(int)*cap); return(arr ? true : false); }
If realloc()
fails it will return nullptr
and the only pointer (arr
) to the original memory region will be gone. Also, instead of return(arr ? true : false);
you should simply use return arr != nullptr;
.
The righttm way to use realloc()
:
bool stack::meminc()
{
int *temp = (int*) realloc(arr, sizeof(*temp) * cap * 2);
if(!temp)
return false;
cap *= 2;
arr = temp;
return true;
}
Also, where is your copy-ctor, assignment operator and d-tor?