【问题标题】:Segmentation fault (core dump) when creating a large 2d dynamic array using c++使用 C++ 创建大型二维动态数组时出现分段错误(核心转储)
【发布时间】:2019-03-30 12:57:02
【问题描述】:

我正在尝试创建一个程序,该程序创建两个 2d 动态数组并将它们相乘并给出输出并根据输入大小 n 计算相乘过程所花费的时间。此代码在输出少于 7 行和 7 列时有效,但当数字超过 8 时会出错。

using namespace std;

int m1c , m1r , m2c , m2r , i , j , k , l;

int** arr1 = new int*[m1c];
int** arr2 = new int*[m2c];
int** multArr = new int*[m1c];

int main(){

    cout << "Enter the Number of rows for matrix 1 :";
    cin >> m1c;

    cout << "Enter the Number of columns for matrix 1 :";
    cin >> m1r;

    cout << "Enter the Number of rows for matrix 2 :";
    cin >> m2c;

    cout << "Enter the Number of columns for matrix 2 :";
    cin >> m2r;

    for (i = 0; i < m1r; i++) {
        arr1[i] = new int[m1c];
        multArr[i] = new int[m1c];
    }

    for (i = 0; i < m2r; i++) {
        arr2[i] = new int[m2c];
    }

    if (m1r != m2c) {
        cout << "Number of rows in the first matrix must be equal to the numbr of columns in the second matrix ";
        return -1;
    }


    for (i = 0; i < m1r; i++) {
        for (j = 0; j < m2c; j++) {

            arr1[i][j] = rand() % 100;
        }
    }

    for (i = 0; i < m2r; i++) {
        for (j = 0; j < m2c; j++) {

            arr2[i][j] = rand() % 100;
        }
    }


    //Displaying the two arrays

    for (i = 0; i < m1r; i++) {
        for (j = 0; j < m1c; j++) {
            cout << arr1[i][j] << " ";
        }
        cout << endl;
    }

    cout << endl;

    for (i = 0; i < m2r; i++) {
        for (j = 0; j < m2c; j++) {

            cout << arr2[i][j] << " ";
        }
        cout << endl;
    }
    delete[] arr1;
    delete[] arr2;

    return 0;

}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

【问题讨论】:

  • 旁注:这里有std::vector&lt;std::vector&gt;
  • 已经使用std::vector&lt;std::vector&lt;int&gt;&gt;了。
  • int** arr1 = new int*[m1c]; 此时m1c0,所以这分配了一个大小为零的数组。
  • 好吧,std::vector&lt;std::vector&lt;int&gt;&gt; 不适用于大量数据(矩阵),通常最好将std::vector&lt;int&gt; 封装在一个类中,该类执行如何按行和列处理的逻辑索引。
  • 在接受它们的值之前,您将 arr1 和 arr2 分配给大小 m1c 和 m2c。更糟糕的是,您没有初始化 m1c 和 m2c,因此它们可能包含垃圾。 [IIRC,如果编译为调试,VS 会将它们初始化为零,如果编译为发布,则保持它们未初始化。] 访问超出分配范围的 arr1 和 arr2 的元素可能是分段错误的原因。此外,您有内存泄漏 - 您删除了 arr1 和 arr2,但没有删除每个元素分配的内存。

标签: c++ arrays segmentation-fault dynamic-arrays coredump


【解决方案1】:

看起来像初始化 arr1 时出错。您使用 m2c 作为列数。你可能是说m1c。

【讨论】:

    猜你喜欢
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多