2011-06-22 69 views
0

我在下面的代碼中遇到了分段錯誤。你能幫我弄清楚嗎?在下面的代碼中,它打印出「OK here」。一旦它釋放內存,它就會顯示分段錯誤。但爲什麼 ?任何解決方案指向矢量的指針:正在獲取分段錯誤

任何幫助,將不勝感激。

#include <iostream> 
#include <cstring> 
#include <vector> 
using namespace std; 

class Cube 
{ 
public: 
    char *str; 

    Cube(int len) 
    { 
     str = new char[len+1]; 
    } 
    Cube(const Cube &c) 
    { 
     str = new char[strlen(c.str) + 1]; 
     strcpy(str, c.str); 
    } 
    ~Cube() 
    { 
     delete [] str; 
    } 
}; 

void foo(vector <Cube> *vec) 
{ 
    for (int i = 0; i < 10; i++) 
    { 
     char in [] = "hello !!"; 
     Cube *c = new Cube(strlen(in)+1); 
     strcpy(c->str, in); 
     vec->push_back(*c); 
     cout << "ok here" << endl; 
     delete [] c; 
    } 
} 

int main() 
{ 
    vector <Cube> vec; 

    foo(&vec); 
    return 0;  
} 
+0

如果您使用'new []''您必須使用'delete []' –

+0

您是否嘗試過使用gdb來查找失敗的行?看起來像問題是你刪除[] - 當它是一個char *的str變量。 – Suroot

回答

4

您還沒有跟上the rule of threeCube沒有實現正確的拷貝賦值運算符。正如其他人提到的,你也有new[]delete錯配,只能以眼淚結束。

也就是說,你不需要使用指針或顯式動態分配任何這些。您應該將new char[]的使用替換爲std::string,並且不要在堆上分配任何Cube對象。在寫得很好的C++程序中,應該很少使用new,應該幾乎不需要使用delete

該程序沒有明確的動態分配,與您期望的程序結果相同,但是正確。注意當你不用擔心動態分配或者明確地破壞你自己時,有多少更清晰的代碼!

#include <string> 
#include <vector> 

struct Cube { 
    std::string str; 
    explicit Cube(std::string const& s) : str(s) { } 
}; 

void foo(std::vector<Cube>& vec) { 
    for (int i = 0; i < 10; ++i) { 
     vec.push_back(Cube("hello !!")); 
    } 
} 

int main() { 
    std::vector<Cube> vec; 
    foo(vec); 
} 

確保您有a good introductory C++ book

+0

非常感謝你!它確實有幫助。 – Miraj

0
delete [] c; 

應該

delete c; 

除此之外,該Cube類本身就是可疑的。最好使用std::string而不是c樣式的字符串。

1

您是delete荷蘭國際集團的Cube數組在這兒:

delete [] c;

但是你沒有分配這裏的數組:

Cube *c = new Cube(strlen(in)+1);

這應該只是:

delete c;

+0

非常感謝! ! – Miraj

0

您使用

delete [] c; 

如果c的分配是這樣的:

Cube * c = new Cube[3]; //3 for example 

然後刪除[]Ç將是適當的。在這種情況下,您應該省略[]。