Search code examples
c++stackdynamic-memory-allocationrealloc

Program crashes because of realloc


I am trying to build a stack that resizes itself and realloc() crashes my program.

Constructor:

Stack::Stack()
{
   st = (int*)malloc(sizeof(int));
   sp = 0;
   length = 1;
}

This is my add() function:

void Stack::add(int item)
{
   if (sp == length)
       Stack::resizeStack(&st, &length, 1);
   st[sp++] = item;
}

Resize function (I use the variable a in order to be able to reuse it for pop) :

void Stack::resizeStack(int **st, int *length, bool a)
{
   if (a == 1)
       *length *= 2;
   else
       *length /= 2;
   realloc(*st, sizeof(int) * (*length));
}

This is how I test my stack:

Stack* myStack = new Stack();
for (int i = 0; i < 10; i += 1) {
    myStack->add(i);
    cout << myStack->getStackSize() << '\n';
}
free(myStack);

I have noticed that the program crashes at the end of the for.

I would appreciate if someone explained what I am doing wrong.


Solution

  • All those people who say, malloc() and free() are a bad idea in C++ are 100% correct. Prefer new and delete over malloc() and free() and prefer standard library containers over your own homebrew stack implementation.

    Anyway, the real issue here is, that realloc() might allocate a new memory block and free the old one. It returns a pointer to the new one.

    The correct call is:

    *st = realloc(*st, sizeof(int) * (*length));
    

    Now *st will store the new pointer and everything is all right.

    Consider to use the standard library, instead of implementing your own fundamental data structures. It has a well designed interface, and is very thoroughly tested.