2017-01-22 65 views
2

我是java程序員,但仍然發現這個C++代碼不工作。當我運行這個項目(Codeblock)時,我得到了分段錯誤。我搜索了互聯網,但無法找到導致此錯誤的確切原因。如圖C++ Segmentation Fault - 這裏有些不同

1)的main.cpp

#include "performancetest.h" 
int main(int argc, char *argv[]) 
{ 
    performancetest *Obj = new performancetest; 
    Obj->test1(); 
    Obj->test2(); 
    Obj->~performancetest(); 
    return 0; 
} 

2)performancetest.cpp

#include "performancetest.h" 
#include <iostream> 
using namespace std; 
performancetest::performancetest() 
{ 
} 

performancetest::~performancetest() 
{ 
} 

void performancetest::test1() 
{ 
    clock_t t1, t2; 
    const int g_n = 500; 
    float TestData[g_n][g_n][g_n]; 
    t1 = clock(); 
    for (int k=0; k<g_n; k++) // K 
    { 
     for (int j=0; j<g_n; j++) // J 
     { 
      for (int i=0; i<g_n; i++) // I 
      { 
       TestData[i][j][k] = 0.0f; 
      } 
     } 
    } 
    //start time t2 
    t2 = clock(); 
    double val = this->diffclock(t1, t2); 
    cout << "Time: " << val << endl; 
} 

void performancetest::test2() 
{ 
    clock_t t1, t2; 
    const int g_n = 500; 
    float TestData[g_n][g_n][g_n]; 
    //start time t1 
    t1 = clock(); 
    for (int k=0; k<g_n; k++) // K 
    { 
     for (int j=0; j<g_n; j++) // J 
     { 
      for (int i=0; i<g_n; i++) // I 
      { 
       TestData[i][j][k] = 0.0f; 
      } 
     } 
    } 
    //start time t2 
    t2 = clock(); 
    double val = this->diffclock(t1, t2); 
    cout << "Time: " << val << endl; 
} 

double performancetest::diffclock(clock_t clock1,clock_t clock2) 
{ 
    double diffticks=clock1-clock2; 
    double diffms=(diffticks)/(CLOCKS_PER_SEC/1000); 
    return diffms; 
} 

3)performancetest.h

#ifndef PERFORMANCETEST_H 
#define PERFORMANCETEST_H 
#include <time.h> 
class performancetest 
{ 
public: 
    performancetest(); 
    void test1(); 
    double diffclock(clock_t, clock_t); 
    void test2(); 
    virtual ~performancetest(); 
protected: 
private: 
}; 
#endif // PERFORMANCETEST_H 

而且,這裏來,段故障下圖 enter image description here

+0

1'使用std'是壞的 - 谷歌它。 2.縮進代碼以使其可讀。 3.或許通過調試器運行它至少會告訴你它發生的線 –

+3

'float TestData [g_n] [g_n] [g_n];'你試圖把一個500MB的數據結構放到堆棧上。通常情況下,堆棧被限制在2MB左右。我懷疑你看到堆棧溢出。使該變量爲'static',或將其分配到堆上。 –

+3

不要直接調用析構函數,在用'new'分配的指針上調用'delete'。 –

回答

1

您的多維數組對於堆棧太大,因此會引發堆棧溢出異常。您必須在堆上分配TestData。

你可以這樣說:

const int g_n = 500; 
typedef float MultiDimArray[g_n][g_n]; 
MultiDimArray* TestData = new MultiDimArray[g_n]; 
//... 
delete[] TestData; //deallocate 
+0

謝謝@GeorgeT –

相關問題