动态 2D 阵列.为什么分段错误?

Dynamic 2D array. Why is segmentation fault?

本文关键字:错误 分段 为什么 2D 阵列 动态      更新时间:2023-10-16

我的问题很简单。看看这个代码。

#include <iostream>
using namespace std;
int main() {
int **arr = new int*[3];
cout << "arr : " << arr << endl;   // It will display address, may be 0xffc1e...
cout << "*arr : " << *arr << endl;    // will be just 0(zero), may be default value
cout << "**arr : " << **arr << endl;    // it will display nothing,  and after that program terminates
cout << "Program completed." << endl;    // This will not display because program terminated
} 

由于检索 **arr,此程序将终止。如果我们摆脱线是**arr。程序将正常完成,并将写入"程序已完成"。GDB说这是分段错误。以便此代码将起作用。

#include <iostream>
using namespace std;
int main() {
int **arr = new int*[3];
cout << "arr : " << arr << endl;   // It will display address, may be 0xffc1e...
cout << "*arr : " << *arr << endl;    // will be just 0(zero), may be default value
cout << "Program completed." << endl;    // This at last will be displayed
} 

因此,如果没有 **arr 所在的行,代码可以正常工作。为什么???

您已经默认初始化了动态数组。它是一个指针数组。默认初始化指针具有不确定的值。读取不确定值的行为是未定义的。

为什么???

因为程序的行为是未定义的。

未定义的行为意味着程序的行为没有任何保证。就语言而言,该程序可能:

  • 生成您期望的输出。
  • 产生您意想不到的输出。
  • 生成要生成的输出。
  • 生成一些您不想要的输出。
  • 根本不产生输出。
  • 崩溃
  • 不崩溃
  • 在另一个系统上的行为不同。
  • 在同一系统上的行为不同。
  • 调试
  • 时的行为有所不同。
  • 只有在度假时表现不同。
  • 出于任何可能的原因,行为不同。
  • 似乎完全没有理由地表现得不同。
  • 始终表现相同
  • 不要那样做。
  • 有任何行为。

应避免未定义的行为。

您已经为 3 个int*分配了空间,但您尚未初始化其中任何一个,因此像*arr一样读取它们会使您的程序具有未定义的行为。

**arr一样,从*arr返回的地址(如果有的话(读取也会使其具有未定义的行为 - 并且经常导致崩溃(如果幸运的话(。

你需要让int*指向某事。初始化指针。另请注意,对于每个new,您只需要一个delete,对于每个new[],您只需要一个delete[]

一些例子:

int main() {
int** arr = new int*[3];
arr[0] = new int[5];  // an array of 5 int
arr[1] = new int[10]; // 10...
arr[2] = new int[20]; // 20...
// use arr
// cleanup
delete[] arr[2];
delete[] arr[1];
delete[] arr[0];
delete[] arr;
} 

请注意,分配的内存仍未初始化,因此在存储数据之前不应从中读取。

如果发生任何事情(如异常(,清理可能很容易被遗忘或跳过。为此,有智能指针。它们一开始可能看起来很尴尬,但会为您省去一个麻烦的世界。

#include <iostream>
#include <memory>
int main() {
std::unique_ptr<std::unique_ptr<int[]>[]> arr = 
std::make_unique<std::unique_ptr<int[]>[]>(3);
arr[0] = std::make_unique<int[]>(5);
arr[1] = std::make_unique<int[]>(10);
arr[2] = std::make_unique<int[]>(20);
// using arr
std::cout << arr[0][4] << "n";  // Using make_unique also default initialized the 
std::cout << arr[1][9] << "n";  // elements in the arrays, so reading from them is 
std::cout << arr[2][19] << "n"; // fine.
} // all arrays held by smart pointers are automatically deleted when arr
// goes out of scope