I allocated the memory but when I call the destructor, it gives me a segmentation fault.
this is the code. am I using the right thing to free the memory?
class plan {
char *symbol;
gro *grow;
public:
plan (int, char[] ); //constructor
~plan ( ); //destructor
};
plan::plan (int num_of_sm, char sm[]){
try {
symbol = new char [strlen(sm) + 1];
}
catch (std::bad_alloc) {
symbol = NULL;
}
if (symbol != NULL) {
if (sm == NULL) {
strcpy (symbol, "");
}
else {
strcpy (symbol, sm);
}
}
gro = new grow [num_of_sm];
}
plan::~plan( ){
delete [ ] symbol;
delete [ ] gro;
}
Use
std::stringand be done with it.Just in case it is not obvious, that will take care of the problem.
But also, to avoid some similar problems and to just understand a bit more of the issues involved, do look up the rule of 3, or as it’s now known with C++11, the rule of 5.