0

I have to create push function with dynamic allocation using new instead of realloc/malloc. I already build program working fine but with malloc and calloc functions and because im starting learning c++ i dont know how to change that to use new instead of malloc. I also should double memory avaible for stack while program run out of avaible memory. Here is stack.cpp code:

#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include "stack.h"

stack::stack()
{
    this->top = 0;
    this->data= (int *)malloc(0 * sizeof(int));
}

stack::~stack()
{
    free(this->data);
}

void stack::clear()
{
    this->top = 0;
}

void stack::push(int a)
{
    i = i * 2;
    assert(this->top < STACKSIZE);
    int *ptr = (int *)realloc(data, (this->top + 1) * sizeof(int));
    if (ptr == NULL)
    {
        return;
    }
    this->data = ptr;
    this->data[this->top++] = a;
}

int stack::pop()
{
    assert(this->top > 0);
    return this->data[--this->top];
}

and there is header file:

#define STACKSIZE 20

class stack
{
public:
    void push(int a);
    int pop();
    void clear();
    stack();
    ~stack();

private:
    int top;
    int *data;
};
MrHardzys
  • 11
  • 3
  • *I already build program working fine* -- You think so? Well, this program has a double `free()` error: `int main() { stack s; stack s2 = s; }` – PaulMcKenzie Oct 25 '20 at 18:18
  • Yes i think so, because my teacher said that it works but i have to rewrite it using only ```new``` operator. – MrHardzys Oct 26 '20 at 08:26
  • *because my teacher said that it works* -- Take that simple program to your teacher. It doesn't work. If your teacher can't see the double free() error, get a new teacher. – PaulMcKenzie Oct 26 '20 at 08:32
  • I wont argue with you maybe you are right maybe dont. But main problem is rewriting that program to program without malloc or realloc and with ```new``` operator and i need help with that – MrHardzys Oct 26 '20 at 11:58
  • No, I am right about your code, without a doubt. Second, if you are learning C++, why was `malloc` introduced in the first place? It should never be used in a C++ program at this stage, or even ever, unless you are advanced and utilizing `placement-new` or something similar. Last, there is no `new[]` equivalent for `realloc`, except to allocate a new space, copy the data to the new space, and deallocate the old space. – PaulMcKenzie Oct 26 '20 at 12:41

0 Answers0