我有這樣定義的類Foo
:刪除陣列給EXC_BAD_ACCESS錯誤
class Foo
{
public:
Foo(int num);
Foo(const Foo& other);
~Foo();
Foo& operator=(const Foo& other);
...
private:
string *fooArray;
void clearMemory();
...
}
Foo::Foo(int num)
{
fooArray = new string[num];
}
Foo::Foo(const Foo& other)
{
*this = other;
}
Foo::~Foo()
{
clearMemory();
}
Foo& operator=(const Foo& other)
{
clearMemory();
fooArray = new string[other.size]; // size is a private variable
memcpy(fooArray, other.fooArray, other.size * sizeof(string));
}
void Foo::someOtherFooFuncion(int newNum)
{
clearMemory(); // crash with Visual Studio, does not crash with g++, but g++ also
// crashes when destructor is called
fooArray = new string[newNum];
}
void Foo::clearMemory()
{
if(fooArray != NULL)
{
delete[] fooArray; // sometimes it crashes here with g++; it always crashes when
// compiling in Visual Studio
fooArray = NULL;
}
}
由於代碼中的註釋指出,這是給我崩潰的時候。我曾嘗試按照GDB的步驟,我得到儘可能
destructing Foo:
@0x7fff5fbff9b0
$26 = {
fooArray = 0x1001009d8,
...
}
並隨後到達delete[] fooArray
,和所有突然
Foo(49858) malloc: *** error for object 0x100100990: pointer being freed was not allocated
不知道在哪裏的0x100100990是從哪裏來的。
我意識到代碼是非常不完整的,但我真的不知道現在開始尋找bug的位置,並且想知道什麼情況可能導致delete[]
錯誤。
編輯:
新增c'tor,德TOR和賦值運算符。我遠離PC,因此代碼可能不是100%準確的。賦值給fooArray並訪問它們雖然工作得很好。
此外,我將非常感謝可能會導致delete[]
拋出錯誤的問題的一般列表,以便我至少可以瞭解在代碼中查找的位置。
編輯2:
所以我也跟着XEO的建議使用std::uninitialized_copy
,現在的代碼工作正常,在G ++編譯。析構函數也可以在Visual Studio中正常工作,但不知怎的,刪除someOtherFooFuncion
中的fooArray會使其崩潰。
還有其他想法嗎?
你有一個默認的構造函數嗎?如果是這樣,你可以發佈它嗎? – hmjd
你記得[規則三](http://stackoverflow.com/questions/4172722)嗎?爲什麼你不使用'std :: vector'? –
@MikeSeymour我有一個ctor和賦值運算符和dtor,但不能使用矢量因爲它是一個類賦值 – wrongusername