In the following program, I declare a global variable (adj_matrix
) for the purpose of using it in different functions. It is defined in another function (init_matrix
).
I tested the program with the test case 3 1 2
and received a segmentation fault.
3 1 2
YES
Segmentation fault: 11
The surprising part is, that when I uncomment the cout
line in the construct_matrix
function, the segmentation fault disappears.
This looks like the case of undefined behavior to me but I'm unable to figure out why and where it occurs. Please help.
Following is the program:
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int> > adj_matrix;
void init_matrix(int size, int val)
{
adj_matrix.reserve(size);
for (int i = 0; i < size; ++i)
{
adj_matrix[i].reserve(size);
for (int j = 0; j < size; ++j)
{
if(i == j)
adj_matrix[i][i] = 0;
else
adj_matrix[i][j] = val;
}
}
}
void construct_matrix(int size, int k, int val)
{
// k denotes how many components we want
for (int i = k - 1; i < size - 1; ++i)
{
adj_matrix[i][i + 1] = val;
adj_matrix[i + 1][i] = val;
// Uncommenting the following line resolves the seg-fault error
// cout << i << endl;
}
}
void print_matrix(int size)
{
for (int i = 0; i < size; ++i)
{
for (int j = 0; j < size; ++j)
cout << adj_matrix[i][j];
cout << endl;
}
}
int main()
{
int n, a, b;
cin >> n >> a >> b;
/*
The solution uses the fact that atleast one of G or G complement is always connected.
In cases where we have to show both are connected (not possible when n is 2 or 3),
we draw a simple graph connected v1 v2 v3...vn. The complement will be also connected (n != 2 and 3)
*/
if(a == 1 && b == 1)
{
if(n == 2 || n == 3)
cout << "NO" << endl;
else
{
cout << "YES" << endl;
init_matrix(n, 0);
construct_matrix(n, 1, 1);
print_matrix(n);
}
}
else if(a == 1)
{
cout << "YES" << endl;
init_matrix(n, 1);
construct_matrix(n, b, 0);
print_matrix(n);
}
else if(b == 1)
{
cout << "YES" << endl;
init_matrix(n, 0);
construct_matrix(n, a, 1);
print_matrix(n);
}
else
cout << "NO" << endl;
return 0;
}
For ones interested in the problem this is a solution to, visit here.
PS: I've checked the bounds in the for
loop in my functions, and they are correct. If this wasn't the case, the program will throw a segmentation fault regardless of the cout
line.