我分配了內存,但是當我調用析構函數時,它給了我一個分段錯誤。 這是代碼。我是否正確地使用內存?C++新建和刪除
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;
}
很難說,因爲你還沒有顯示出你的班級的完整定義。請閱讀http://sscce.org。最可能的解釋是'symbol'不是一個有效的指針。 – 2012-04-06 23:24:31
你的構造函數是什麼樣的? – 2012-04-06 23:24:52
你如何以及在哪裏爲符號分配內存並增長? – Haatschii 2012-04-06 23:26:39