动态 2D 阵列.为什么分段错误?
Dynamic 2D array. Why is segmentation fault?
我的问题很简单。看看这个代码。
#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
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 为什么我使用 std::copy() 收到运行时错误(分段错误)?
- 为什么我的代码包含错误分段错误(核心转储)?
- 为什么会出现此错误?- 分段错误(核心转储)
- 意外的运行时错误(分段错误)
- C++将文本文件读入数组,运行错误:分段错误
- mmap 错误:分段错误/指针无效错误
- 在我的代码中找不到错误....分段错误
- 错误:分段故障(核心转储)阵列
- 用string.h将错误分段到队列中
- c++字符串流转换错误:分段错误
- 为什么我的代码显示错误分段错误(核心转储)