I have the following code and am not sure why am I getting the heap corruption detected error when it hits the destructor of Myclass. I believe I am deallocating the memory properly ??
#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";
}
EDIT: (Fixed code)
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);
}
in main(), I also added
delete a;
before calling return 1;