【问题标题】:Segmentation fault in c++C ++中的分段错误
【发布时间】:2015-04-13 08:34:31
【问题描述】:
#include<iostream>   
using namespace std; 

class Toto{  
private:  
   int w;   
public:  
    Toto();     //constructor   
    int *veg;     //pointer veg  
        void  func9()   
    {   
         veg =new int [4] ; //dynamic mem allocation     
    }   
        void func7()   
    {   
        delete [] veg;  //free mem    
    }      
};                                                                  

Toto::Toto() 
{   
    cout <<" contructor is here: " << endl;   
} 

int main () 
{ 

Toto pen;
cout << "enter numbers: ";  
for (int i=0;i<4;i++) 
{ 
    cin >> pen.veg[i];  
}
cout << endl;  
for (int i=0;i<4;i++) 
{ 
    cout << pen.veg[i] << " " << endl;  
}

return 0;
} 

上面的代码由于某种原因产生了 Seg Fault。 输入数字后,此代码会产生段错误! 乱码请见谅,初学者先谢谢了!

【问题讨论】:

  • veg 没有分配存储空间 - 您需要先调用 func9() 方法来分配一些存储空间。
  • 你有什么理由不在Toto中使用int veg[4]

标签: c++ segmentation-fault


【解决方案1】:

veg 未分配。在构造函数中分配它并在析构函数中删除的最佳方法,如下所示:

class Toto{  
private:  
   int w;   
public:  
    int *veg;     //pointer veg 
    Toto() {
        veg =new int [4] ; //dynamic mem allocation
    };     //constructor   


    ~Toto() {   
        delete [] veg;  //free mem    
    };      
};       

或者您应该在使用veg之前致电func9()

【讨论】:

  • 感谢您的帮助
【解决方案2】:

如果你坚持动态分配,可以这样操作:

class Toto {  
private:  
   int w;   
public:  
    Toto();     //constructor   
    ~Toto();    //destructor
    int * veg;     //pointer veg  
};

Toto::Toto() : veg(new int[4])
{   
    cout <<" contructor is here: " << endl;   
}

Toto::~Toto() {
    delete[] veg;
}

【讨论】:

    【解决方案3】:

    veg 仅在您调用func9() 尝试使用它之前设置为有效值。如果你要这样做,你可以随意玩veg[0]veg[3],只要你没有调用func7()来释放内存。

    所需成员变量的分配通常应在构造函数中完成(并在析构函数中解除分配),避免此类问题。

    构造函数的主要优点之一是确保在对象的任何使用参与之前正确地完全初始化变量。

    一种方法是修改你的代码:

    #include<iostream>
    using namespace std;
    
    class Toto{
        private:
            int w;
        public:
            int *veg;
            Toto() { veg = new int[4]; }
            ~Toto() { delete[] veg; }
    };
    
    int main (void) {
        Toto pen;
    
        cout << "enter numbers: ";
        for (int i = 0; i < 4; i++)
            cin >> pen.veg[i];
        cout << endl;
    
        for (int i = 0; i < 4; i++)
            cout << pen.veg[i] << " " << endl;
    
        return 0;
    }
    

    那么你完全不用担心在尝试使用对象的组件之前是否调用了成员函数。

    【讨论】:

    • @Algo,我看到你没有接受我的答案,所以我不得不假设你已经发现了它不再是最佳答案的一些原因。也许,如果你能分享这个原因,我很乐意修复它或进一步解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    相关资源
    最近更新 更多