如果打印后输入整数,则C++分段故障,但其他情况下可以
C++ Segmentation Fault if integer is input after printed, but ok otherwise
以下源代码编译并运行精细
#include <cstdio>
#include <iostream>
using namespace std;
int main() {
int t;
cout << t << endl; // the seg fault / rte is for this
cout << t+10 << endl;
int mat[0];
int mat2[t+10];
for (int i = 0 ; i<100 ; i++) {
//cout << mat[i] << endl;
}
cout << sizeof(mat)/sizeof(int) << endl;
cout << sizeof(mat2)/sizeof(int) << endl;
//cin >> t;
return 0;
}
但是,如果我取消注释cin >> t
,则会导致Segmentation Fault。
#include <cstdio>
#include <iostream>
using namespace std;
int main() {
int t;
cout << t << endl; // the seg fault / rte is for this
cout << t+10 << endl;
int mat[0];
int mat2[t+10];
for (int i = 0 ; i<100 ; i++) {
//cout << mat[i] << endl;
}
cout << sizeof(mat)/sizeof(int) << endl;
cout << sizeof(mat2)/sizeof(int) << endl;
cin >> t;
return 0;
}
里面发生了什么?
我发现有问题
#include
#include
using namespace std;
int main() {
int t;
cout << t << endl; // the seg fault / rte is for this
cout << t+10 << endl;
int mat[0];
int mat2[t+10]; // <=== HERE IS THE PROBLEM
for (int i = 0 ; i<100 ; i++) {
//cout << mat[i] << endl;
}
cout << sizeof(mat)/sizeof(int) << endl;
cout << sizeof(mat2)/sizeof(int) << endl;
cin >> t;
return 0;
}
您正在创建一个可变大小的数组,这没有问题,但您是基于未初始化的变量定义大小的。C/C++上未初始化的局部变量,没有默认值,它可以具有从堆栈垃圾中获得的ANY值
为了测试这一点,我用奇怪的(但可能的)t值编译了程序,以获得SegmentationFaults:
int main() {
int t = -22;
...
int mat[0];
int mat2[t+10];
int main() {
int t = 0xdeadbeef;
...
int mat[0];
int mat2[t+10];
你可以得到任何一个值,但它会随机失败,我使用cin>>t会在编译器优化中更改某些变量,从而导致堆栈值或类似的事情,但这是完全不可预测的,你可以认为它几乎是随机
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 分段故障(堆芯转储)矢量
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- C++中的动态铸造故障
- 数组的指针从不分段故障
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- vscode g++链路故障:体系结构x86_64的未定义符号
- 访问被拒绝后,c++中的故障保护代码
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 在其他文件中创建类时在 c++ 项目中不起作用
- Windows 10-使用gtkmm-3.0库和g++[包括再现]的分段故障
- 类与私有变量的其他类之间的线程安全性
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- GlobalAlloc而不是其他分配方法
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 断言中的Fold表达式在某些计算机上编译,但在其他计算机上不编译
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- C++-一个函数会使其他函数发生故障
- 如果打印后输入整数,则C++分段故障,但其他情况下可以