0

Possible Duplicate:
Matrix Arithmetic using Vectors in C++ causing segmentation faults

I created this simple code in C++ to assign some values to a dynamic matrix:

unsigned N = 1000;
vector<vector<double> > Matrix;

for (unsigned i=0; i<(N-1); ++i) {
    for (unsigned j=0; j<(N-1); ++j) {

        if ((i>(N/4-1) && i<(3*N/4-1)) || (j>(N/4-1) && j<(3*N/4-1)))
            Matrix[i][j] = 1;

        else if (i==0 || i==(N-1) || j==0 || j==(N-1))
            Matrix[i][j] = 0;
}
}

The compiler does not return any problem, but when I try to run the program, it returns: Segmentation Fault. Where is my mistake?

Thank you for your attention.

Community
  • 1
  • 1
Pippo
  • 1,543
  • 3
  • 21
  • 40

2 Answers2

1

You are just creating two empty vectors, and using the operator[] is undefined behaviour. They are like arrays of size 0, if such a thing was possible.

You have to create the vectors with a capacity, and each element will be default-initialised to 0:

vector<vector<double>> Matrix(N, vector<double>(N));

The first argument is the size of the outer vector, and the second is the value to copy into each element, which is itself a vector of N doubles.

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
0

If the code you have listed is the exact code causing the problem, your issue is that you haven't actually given the "matrix" a size.

vector<vector<double> > Matrix ( N, vector<double>(N) );

would do that.

In future to debug segfaults, you can start with by compiling with no optimisations and debug symbols on, then running in a debugger (such as gdb) and backtracing after the sefault. The backtrace would also be useful when asking for help.

111111
  • 15,686
  • 6
  • 47
  • 62