Tengo el siguiente código y no estoy seguro de por qué recibo el error de corrupción detectado en el montón cuando golpea el destructor de Myclass. Creo que estoy desasignando la memoria correctamente?Se detectó corrupción en el montón después del bloque normal
#include <iostream>
#include <vector>
using namespace std;
class MyClass{
private:
char* mp_str;
public:
MyClass():mp_str(NULL){}
~MyClass(){
delete [] mp_str;
}
void setString(const char* str);
void printString();
};
int main(){
MyClass* a = new MyClass();
std::vector<MyClass> myVector;
myVector.push_back(*a);
a->setString("Hello World");
myVector[0].setString("Goodbye world");
a->printString();
myVector[0].printString();
return 1;
}
void MyClass::setString(const char* const str){
if(!str)
return;
size_t len = strlen(str);
if(!this->mp_str){
this->mp_str = new char[len];
memset(mp_str, 0, len+1);
}
strncpy(mp_str, str, len);
}
void MyClass::printString(){
if(this->mp_str)
cout << mp_str;
else
cout << "No string found";
}
EDITAR: (Código fijo)
void MyClass::setString(const char* const str){
if(!str)
return;
size_t len = strlen(str);
if(!this->mp_str){
this->mp_str = new char[len+1];
memset(mp_str, 0, len+1);
}
strncpy(mp_str, str, len);
}
en main(), también añadió
delete a;
antes de llamar retorno 1;
necesitan la [regla de tres] (http://stackoverflow.com/questions/4172722/what- is-the-rule-of-three). – jxh
también se filtra el objeto en 'a' –
@yurikilochek: de acuerdo. arregló eso. – brainydexter