I am trying to write a simple stack with dynamic memory allocation. Must be with new/delete. Sorry, if it's trivial but I would appreciate if someone could take a look. Any advice is appreciated.
It works, but I want to make peace with valgrind --leak-check=full
stack.cpp
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include "stack.h"
#include <algorithm>
#define INITIAL_STACKSIZE 1
stack::stack()
{
top = 0;
size = INITIAL_STACKSIZE;
data = new int[size];
}
stack::~stack()
{
// delete [] ptr; makes it worse "free(): double free detected in tcache 2
// Aborted (core dumped)"
delete [] data;
}
void stack::push(int a)
{
if(top >= size)
{
int new_size = size * 2;
ptr = new int[new_size];
std:: copy(data, data + top, ptr);
data = ptr;
size = new_size;
}
data[top++]=a;
}
int stack::pop()
{
assert(top>0);
return data[--top];
}
stack.h
class stack
{
public:
void push(int a);
int pop();
void clear();
stack();
~stack();
private:
int top;
int size;
int *data;
int *ptr;
};
teststack.cpp
#include <stdio.h>
#include "stack.h"
int main()
{
stack s1;
stack s2;
s1.push(1);
s1.push(2);
s2.push(5);
s2.push(6);
printf("%d %d\n",s1.pop(),s2.pop());
printf("%d\n",s1.pop());
printf("%d\n",s2.pop());
return 0;
}