So I have to implement a stack using an array built in a class, and if the "stack" ever fills up, I am supposed to increase the size of the array which I attempted, and failed. So I am just curious as to what I need to change in order to make this work.
class AbstractStack { private: Type elements; // elements in the array Type max; Type *s; public: AbstractStack(Type num) { //CONSTRUCTOR elements= -1; this->max = num; s = new Type[max]; } /* bunch of code that does not apply to this issue */ void push ( Type e ) { if (elements + 1 == max) { cout << "Stack at max size, WIll increase size of array and add item" << endl; Type *temp = new Type[max + (max/2)]; for (int i = 0; i < elements+1; i++) { temp[i] = s[i]; } s = temp; delete temp; elements++; s[elements] ; return; } else { elements++; s[elements] = e; } } When I take the size of this new s, I get the correct size of 1 larger than before because this function is only called when trying to add 1 element to the full stack, but when I attempt to use the top function, it just gives me 0 then I get like 50 lines of error codes starting in:
*** Error in `./a.out': double free or corruption (top): 0x0000000000c53cf0 *** ======= Backtrace: ========= /lib64/libc.so.6(+0x7c619)[0x7fa34a270619] ./a.out[0x400c38] ./a.out[0x400b48] /lib64/libc.so.6(__libc_start_main+0xf5)[0x7fa34a215c05] ./a.out[0x400979]
temptos. You should swap those two.returnwhere it is, and you probably need to deletesinstead oftemp, then assigntemptos.