[問題] delete 與 delete[] 行為上的差異?

看板C_and_CPP作者 (......)時間12年前 (2013/03/18 20:15), 編輯推噓3(302)
留言5則, 4人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) dev c++ 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 在解構子裡面Fruit::~Fruit(){ delete color; } delete color這樣寫正確嗎~? 還是要寫成delete []color 我嘗試過好像兩種寫法都可以,本身是用dev c++ compile 不知道對不對, 除了dev c++外還有什麼IDE可以拿來寫C呢~? dev c++有些沒有include的東西都可以直接用很怪 VC++要正版的,有抓了eclipse,但是沒辦法compile 餵入的資料(Input): 預期的正確結果(Expected Output): 錯誤結果(Wrong Output): 程式碼(Code):(請善用置底文網頁, 記得排版) #include<iostream> using namespace std; class Fruit{ public: double weight; char *color; Fruit(double,char *); virtual ~Fruit(); }; Fruit::Fruit(double w,char *col){ weight=w; color=new char[strlen(col)+1]; strcpy(color,col); } Fruit::~Fruit(){ delete color; } class Apple:public Fruit{ public: char *variety; Apple(double,char*,char*); ~Apple(); }; Apple::Apple(double w,char* col,char *var):Fruit(w,col){ variety=new char[strlen(var)+1]; strcpy(variety,var); } Apple::~Apple(){delete variety;} int main(){ Fruit *basket[20]; int i; double weight=100.5; char color[128]="紅色"; char variety[128]="富士"; for(int i=0;i<20;i++) basket[i]=new Apple(weight,color,variety); for(int i=0;i<10;i++) delete basket[i]; for(int i=0;i<20;i++) cout<<basket[i]->color<<endl; system("pause"); return 0; } 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.252.246.123

03/18 20:32, , 1F
觀念: new 來的就 delete, new[] 來的就 delete[]
03/18 20:32, 1F

03/19 08:56, , 2F
沒記錯的話,new[]出來的用delete是undefined behavior
03/19 08:56, 2F

03/19 08:56, , 3F
03/19 08:56, 3F

03/20 10:22, , 4F
之前問,其實沒差,起始位址給對就不會leak
03/20 10:22, 4F

03/20 11:02, , 5F
delete [] 會依序呼叫每個元素的解構子,delete 則不會
03/20 11:02, 5F
文章代碼(AID): #1HHmLGUI (C_and_CPP)