Estoy aprendiendo a programar en C++ usando memoria dinámica y para esto decidí implementar una pila basada en arreglos.
Hace poco conocí la herramienta valgrind, la cual me avisa si tengo bloques de memoria sin liberar, y a pesar de que el programa corre sin problemas, a la hora de revisarlo con valgrind me aparece el siguiente error:
valgrind ./main
==7787== Memcheck, a memory error detector
==7787== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==7787== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==7787== Command: ./main
==7787==
==7787== Mismatched free() / delete / delete []
==7787== at 0x4C3123B: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7787== by 0x1089BB: Pila::~Pila() (in /home/josue/Escritorio/PIla/Pila basada en arreglos/main)
==7787== by 0x108B16: main (in /home/josue/Escritorio/PIla/Pila basada en arreglos/main)
==7787== Address 0x5b7dc80 is 0 bytes inside a block of size 4,000,000 alloc'd
==7787== at 0x4C3089F: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7787== by 0x10899B: Pila::Pila() (in /home/josue/Escritorio/PIla/Pila basada en arreglos/main)
==7787== by 0x108ADF: main (in /home/josue/Escritorio/PIla/Pila basada en arreglos/main)
==7787==
==7787==
==7787== HEAP SUMMARY:
==7787== in use at exit: 0 bytes in 0 blocks
==7787== total heap usage: 2 allocs, 2 frees, 4,072,704 bytes allocated
==7787==
==7787== All heap blocks were freed -- no leaks are possible
==7787==
==7787== For counts of detected and suppressed errors, rerun with: -v
==7787== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Parte del programa es el siguiente:
typedef int tElemPila;
class Pila{
int maxSize;
int stackSize;
tElemPila* Array;
public:
Pila();
~Pila();
void clear();
int push(tElemPila item);
int pop();
tElemPila topValue();
int length();
void print();
};
Pila::Pila(){
maxSize = 1000000;
Array = new tElemPila[maxSize];
stackSize = 0;
}
Pila::~Pila(){
delete Array;
}
void Pila::clear(){
delete Array;
Array = new tElemPila[maxSize];
stackSize = 0;
}
Espero puedan ayudarme. Muchas gracias de antemano.
Array = new tElementPila[maxSize]
, en el delete lo tienes que indicar así:delete [] Array