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
1'使用std'是坏的 - 谷歌它。 2.缩进代码以使其可读。 3.或许通过调试器运行它至少会告诉你它发生的线 –
'float TestData [g_n] [g_n] [g_n];'你试图把一个500MB的数据结构放到堆栈上。通常情况下,堆栈被限制在2MB左右。我怀疑你看到堆栈溢出。使该变量为'static',或将其分配到堆上。 –
不要直接调用析构函数,在用'new'分配的指针上调用'delete'。 –