C ++分段错误 - 这里有所不同

时间:2017-01-22 15:34:25

标签: c++ segmentation-fault

我是java程序员,但仍然发现这个c ++代码不起作用。当我运行这个项目(Codeblock)时,我得到了分段错误。我搜索了互联网,但无法找到导致此错误的确切原因。

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

1 个答案:

答案 0 :(得分:1)

您的多维数组对于堆栈来说太大了,因此抛出了堆栈溢出异常。您必须在堆上分配TestData。

你可以这样做:

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