2015-09-04 56 views
0

我试过了所有的东西,但是代码不起作用,我不明白为什么。使用'删除'操作符清除内存时出现'Debug Assertion Failed'错误

我有两个类。 这一个是基类:

class Vegetables 
{ 
    private: 
     char *nameStr; 
     char *countrySrc; 
     int seasonRd; 
    public: 
     Vegetables() 
     { 
      cout << "Default constructor for Vegetables" << endl; 
      nameStr = new char[20]; 
      nameStr = "Unknown"; 
      countrySrc = new char[20]; 
      countrySrc = "Unknown"; 
      seasonRd = -1; 
     } 

     virtual ~Vegetables() 
     { 
      delete[]nameStr; //Here happens the error (_crtisvalidheappointer(block)) 
      delete[]countrySrc; 
      cout << "Destructor for Vegetables" << endl; 
     } 
}; 

它继承类的继承单位“:

class InhUnit : public Vegetables 
{ 
    private: 
     Delivery delivery_; 
     Vegetables vegetables; 
     int quantity; 
     int price; 
     int delivPrice; 

    public: 
     InhUnit() :Vegetables(),delivery_(OwnCosts), vegetables(), quantity(-1), price(-1), delivPrice(-1) 
     { 
      cout << "Default constructor for Inherited Unit" << endl; 
     } 

     ~InhUnit() 
     { 
      cout << "Destructor for Inherited Unit" << endl; 
     } 
}; 

什么可能是这个错误弹出的原因吗?

回答

5

那不是你如何复制字符串,请使用strcpy代替

Vegetables() 
    { 
     cout << "Default constructor for Vegetables" << endl; 
     nameStr = new char[20]; 
     strcpy(nameStr, "Unknown"); 
     countrySrc = new char[20]; 
     strcpy(countrySrc, "Unknown"); 
     seasonRd = -1; 
    } 

什么你做的是分配一些内存并将其分配给一个指针。然后在下一行中,您将指针指向指向一个字符串,而不是将该字符串复制到您分配的内存中。

当你调用delete[]因为指针没有指向你分配给你的内存的错误。

+0

非常感谢您! –

0

您应该使用像std :: string这样的字符串类来避免这种指针问题。

0

纠正代码

class Vegetables { 
private: 
    std::string nameStr; // Use std::string instead of C-style string 
    std::string countrySrc; 
    int   seasonRd; 

public: 
    // Use constructor initialization list 
    Vegetables() : nameStr("Unknown"), countrySrc("Unknown"), seasonRd(-1) { 
     cout << "Default constructor for Vegetables" << endl; 
    } 

    virtual ~Vegetables() { 
     cout << "Destructor for Vegetables" << endl; 
    } 
}; 
相关问题