2015-05-11 48 views
0

我試圖從Stroustroup的C++書籍中運行此代碼,我添加了一些代碼,因爲書中沒有提供任何東西。我一直在觸及以下問題。我知道在這裏有同樣的錯誤有多個問題,但我的代碼是不同的,因此這個問題。無效的對象訪問C++

的錯誤是

副本(5826,0x7fff76b09300)的malloc:*錯誤對象0x7ff6a9404c18:用於釋放對象不正確的校驗 - 對象被釋放後,可能被修改。 *設置斷點malloc_error_break調試 中止陷阱:6

#include<stdio.h> 
#include<iostream> 

using namespace std; 
class Vector { 
private: 
    double * elem; // elem points to an array of sz doubles 
    int sz; 
public: 
    Vector(int s) { 
     sz = s; 
     elem = new double[sz]; 
     for (int i = 0; i<sz; i++) { 
      elem[i] = i; 
     } 
    } 
    ~Vector() { delete[] elem; } // destructor: release resources 
    Vector(const Vector& a); // copy constructor 
    Vector& operator=(const Vector& a); // copy assignment 
    double& operator[](int i); 
    const double& operator[](int i) const; 
    int size() const; 
}; 


Vector::Vector(const Vector& a) // copy constr uctor 
{ 
    elem = new double[sz], // allocate space for elements 
     sz = a.sz; 
    for (int i = 0; i != sz; ++i) // copy elements 
     elem[i] = a.elem[i]; 
} 


double& Vector::operator[](int k) { 
    return this->elem[k]; 
} 


Vector& Vector::operator=(const Vector& a) // copy assignment 
{ 
    double* p = new double[a.sz]; 
    for (int i = 0; i != a.sz; ++i) 
     p[i] = a.elem[i]; 
    delete[] elem; // delete old elements 
    elem = p; 
    sz = a.sz; 
    return *this; 
} 


int main() { 
    Vector v1(10); 
    Vector v2 = v1; 
    v1[0] = 2; 
    v2[1] = 3; 
    cout << v1[0] << "\n"; 
    return 0; 
} 

回答

1

你的拷貝構造函數應該扭轉兩行,因爲你沒有爲sz設置的值呢。

Vector::Vector(const Vector& a) // copy constructor 
{ 
    elem = new double[sz]; 
    sz = a.sz; 
    for (int i=0; i!=sz; ++i) 
     elem[i] = a.elem[i]; 
} 

所以,你可以做

Vector::Vector(const Vector& a) // copy constructor 
{ 
    sz = a.sz; 
    elem = new double[sz]; 
    for (int i=0; i!=sz; ++i) 
     elem[i] = a.elem[i]; 
} 
1

你的拷貝構造函數有一個錯誤:

elem = new double[sz], // allocate space for elements 

這是使用正在創建的對象的sz,並sz在這種情況下,不是招尚未初始化。它應該是:

elem = new double[a.sz], // allocate space for elements 

我也建議你使用逗號也避而遠之,並將其更改爲

elem = new double[a.sz];//<--semicolon instead of comma 
+0

謝謝,這一個擺脫了我的注意,它很難找到這個與我得到的錯誤信息,爲什麼系統會拋出這個錯誤? –

1

看拷貝構造函數。 sz在聲明elem = new double[sz]中使用時未初始化,因此訪問其值會導致未定義的行爲。大概你打算這個陳述是elem = new double[a.sz]

這樣做的結果是,在main()中,定義/初始化Vector v2 = v1產生未定義的行爲。

0

這個拷貝構造函數是無效

Vector::Vector(const Vector& a) // copy constr uctor 
{ 
    elem = new double[sz], // allocate space for elements 
     sz = a.sz; 
    for (int i = 0; i != sz; ++i) // copy elements 
     elem[i] = a.elem[i]; 
} 

起初,你B平均值設定SZ或使用在運營商新a.sz

Vector::Vector(const Vector& a) // copy constr uctor 
{ 
    sz = a.sz; 
    elem = new double[sz], // allocate space for elements 

    for (int i = 0; i != sz; ++i) // copy elements 
     elem[i] = a.elem[i]; 
} 

要考慮到最好是定義數據成員sz爲具有類型size_t代替int