我正在用C++構造一個Polynomial類。目前,我正在讀入輸入並創建一個具有度數和係數(雙精度)數組的多項式對象。SegFault類中的析構函數[已更新]
Ex。
6x^3+7.4x^2-3.0x+9
Polynomial
----------
degree = 3
coefficients[0] = 6
coefficients[1] = 7.4
coefficients[2] = 3.0
coefficients[3] = 9
我在刪除我的班級實例時出現錯誤。我不知道這個問題是完全...連同SEGFAULT
我的錯誤看起來像什麼:
Segmentation fault: 11
0x00007ffff71fdfbd in malloc_printerr (ptr=<optimized out>,
str=0x7ffff7304ad8 "free(): invalid next size (fast)", action=<optimized out>) at malloc.c:4983
_int_free (have_lock=0, p=<optimized out>, av=<optimized out>) at malloc.c:3850
__GI___libc_free (mem=<optimized out>) at malloc.c:2960
請幫幫忙,謝謝!
我的構造是這樣的:
/* Constructor for Polynomial */
Polynomial::Polynomial()
{
degree = 0;
coefficients = new double [1];
coefficients[0] = 0;
}
Polynomial::Polynomial (const Polynomial & P)
{
*this = P;
}
賦值運算符:
Polynomial & Polynomial::operator = (const Polynomial & P)
{
if (this != &P){
degree = P.degree;
coefficients = new double [P.degree + 1];
for (int i = 0; i <= P.degree; i++)
coefficients[i] = P.coefficients[i];
}
return *this;
}
我的析構函數看起來像:
/* Destructor for Polynomial */
Polynomial::~Polynomial()
{
delete [] coefficients; <--ERROR HERE
}
我在我的main()的實現看起來是這樣的:
vector<Polynomial> Polys;
Polynomial *P1 = new Polynomial();
...
P1->degree = degreeInt;
P1->coefficients[idx] = coefficient;
Polys.push_back(*P1);
delete P1; <-- ERROR HERE
// Pushed Polynomial to Vector, create a new Polynomial object
P1 = new Polynomial();
你需要一個賦值操作符和拷貝構造函數,但就是爲什麼'coefficients'應該首先被動態分配無明顯原因。 – EJP
'P1->係數[idx] =係數;'可能是越界訪問。 –
您的第一步是瞭解內存泄漏和段錯誤之間的區別。 –