Reputation: 7636
I am java programmer but still finding this c++ code not working. When I run this project (Codeblock), I get the segmentation fault. I searched internet but couldn't find exactly what causing this error.
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
And, here comes, segmentation fault as shown in below picture
Upvotes: 2
Views: 279
Reputation: 504
Your multidimensional arrays are too big for the stack, so a stack overflow exception is thrown. You must allocate TestData on the heap.
You can do it like this:
const int g_n = 500;
typedef float MultiDimArray[g_n][g_n];
MultiDimArray* TestData = new MultiDimArray[g_n];
//...
delete[] TestData; //deallocate
Upvotes: 1