c++ - 无法找到未定义行为的原因

标签 c++ global-variables undefined-behavior

在下面的程序中,我声明了一个全局变量 (adj_matrix),以便在不同的函数中使用它。它在另一个函数 (init_matrix) 中定义。

我用测试用例 3 1 2 测试了程序并收到了段错误。

3 1 2
YES
Segmentation fault: 11

令人惊讶的是,当我取消注释 construct_matrix 函数中的 cout 行时,段错误消失了。

对我来说这看起来像是未定义行为的情况,但我无法弄清楚它发生的原因和位置。请帮忙。

程序如下:

#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;
}

如果对这个问题的解决方案感兴趣,请访问 here .

PS:我已经检查了函数中 for 循环中的边界,它们是正确的。如果不是这种情况,无论 cout 行如何,程序都会抛出一个段错误。

最佳答案

此代码中未定义行为的原因/原因之一是使用 operator[] 访问尚未创建的 vector 元素。

来自 http://www.cplusplus.com/reference/vector/vector/operator[]/ :

A similar member function, vector::at, has the same behavior as this operator function, except that vector::at is bound-checked and signals if the requested position is out of range by throwing an out_of_range exception.

Portable programs should never call this function with an argument n that is out of range, since this causes undefined behavior.

reserve 不会创建 vector 的新元素。它只是确保 vector 为它们分配了足够的内存。如果您想创建可以访问的新元素,请使用 resize。 ( https://stackoverflow.com/a/7397862/3052438 )

我还建议在解决第一个问题后,仔细检查所有 vector 访问是否存在越界索引。

关于c++ - 无法找到未定义行为的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50814357/

相关文章:

c++ - 如何检测当前屏幕分辨率?

c++ - gethostbyname 替换 IPv6 地址

c - a[i++] = 3 是否未定义?

c++ - 如何制作具有自定义移位值的模板

c++ - 为了便于阅读,在 GDB 上缩写 C++ 模板?

c++ - 我在 SFML : How does it rotate member shapes correctly on its own? 中的 'body' 类

powershell - 函数中更改的全局变量无效

c++ - 堆分配的 const 对象与非 const 对象有何不同?

JQuery 读取 JSON(全局/局部变量)

c - 在 C 中试验全局变量和函数