C++ C++;如果打印后输入整数,则分割错误,否则为ok
以下源代码编译并运行良好C++ C++;如果打印后输入整数,则分割错误,否则为ok,c++,C++,以下源代码编译并运行良好 #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+1
#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;
}
你可以得到任何值,它会随机失败,我使用CIN > T改变编译器优化中的某些变量,从而改变堆栈值或类似的东西,但是它是完全不可预测的。你可以使用一个未初始化变量(main 2和3行)来考虑它几乎是随机的
ub,第二个cout
。使用所有警告和调试信息编译(例如g++-Wall-g
)。然后使用调试器(gdb
)请注意,没有常量表达式的数组声明是GCC扩展。您应该使用C++容器类来代替。另外,确保初始化变量。当您用0声明时,您似乎还认为在mat
中有100个元素。有关更详细的解释,请参阅。@Beta,谢谢。这门语言的一个完全未知的面孔向我展示了自己:)我很确定你没有理解核心问题。我知道这是未定义的行为,你说的都是真的。但是原始问题有两个代码示例,第一个运行时没有分段错误(在多个环境中),而另一个没有。通常,由未初始化变量引起的问题会在代码中持续存在,但在本例中,当某段代码丢失时,问题似乎消失了。不管怎样,我在这里找到了可能的原因
#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;
}
int main() {
int t = -22;
...
int mat[0];
int mat2[t+10];
int main() {
int t = 0xdeadbeef;
...
int mat[0];
int mat2[t+10];