Why do i get the error “malloc(): corrupted top size”?

I’m trying to implement stack using dynamic arrays:

class stackArray{
public:
    stackArray(){mainArr = new int[arrSize];}

    void push(int data){
        if(curr > arrSize){
            int *newArr = new int[arrSize*2];
            for(int i = 0 ; i < arrSize; ++i){
                newArr[i] = mainArr[i];
            }
            arrSize *= 2;
            delete []mainArr;
            mainArr = newArr;
        }
            mainArr[++curr] = data;
    }
    void print(){ // debug
        for(int i = 0; i < arrSize; ++i){
            std::cout << mainArr[i];
        }
        std::cout << std::endl;
    }

private:
    int *mainArr;
    int curr = -1;
    int arrSize = 10;
};

and for some reason, whenever curr > arrSize is true and allocate a new memory called newArr it produces malloc(): corrupted top size. I’m still new in dynamic memory and I don’t understand this error. can anybody explain it and how to solve this?

Answer

Initially the data member curr is equal tp -1.

Now for simplicity let’s assume that the initial value of the data member arrSize is equal to 1. That is the constructor dynamically allocated an array with one element.

So as curr is not greater than arrSize you are setting mainArr[0] within the function push. Now curr is equal to 0

mainArr[++curr] = data;

And again curr is not greater than arrSize. So in a next call of push you are trying to overwrite memory that does not belong to the dynamically allocated array that is you are trying to access memory using the expression mainArr[1].

You need to update correctly the if statement within the function. For example

if( !( curr + 1 < arrSize ) ){

Pay attention to that the function print in general is not correct because you are not initializing all elements of a newly allocated dynamically array.

void print(){ // debug
    for(int i = 0; i < arrSize; ++i){
        std::cout << mainArr[i];
    }
    std::cout << std::endl;
}