堆栈上价值的腐败
Corruption of value on the stack
本文关键字:堆栈 更新时间:2023-10-16
在下面的代码中,我发现在阅读了一定数量的输入后,N的值被替换为(至0(。我相信这是因为我在堆栈上分配了K和S数组。我想知道我的结论是否正确?我曾经在C中很长一段时间在C中进行编码,然后切换到Python和其他脚本语言。因此,我的内存管理似乎已经折腾了。
ofstream cop("op1.txt");
ifstream cinp("in1.txt", ios::binary);
int T, t=1;
cinp >> T;
for(;t <= T;t++){
fflush(stdin);
long D;
int N;
long K[N], S[N];
cinp >> D >> N;
double times[N], max = 0;
cout << D << " " << N << endl;
for(long i=0; i<N; i++) {
cout << D << " " << N << endl; // Output of this line is shown below till N gets replaced by 0
cinp >> K[i] >> S[i];
times[i] = (1.0 * (D - K[i]))/S[i];
if(max < times[i])
max = times[i];
}
cout << D << " " << N << endl;
if(t == 3) {
cout << D << " " << N << endl;
for(int i=0;i<N;i++)
cout << K[i] << " " << S[i] << endl;
}
cop << "Case #" << t << ": " << std::setprecision(6) << std::fixed << D/max << endl;
}
一瞥何时被替换
912786011 100 <--- Needs to read 100 nos as N is 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 100
912786011 0 <---------------- Became 0
另外,我想知道我的结论是否正确,那么可以在堆栈上分配的大量内存(没有新的(?
deidei正确地说,您已经错误地使用了GCC的VLA扩展。
https://gcc.gnu.org/onlinedocs/gcc/variable-length.html
分配存储时,计算一次数组的长度一次 并在阵列的范围内被记住,以防万一您访问它 使用大小。
因此,您必须分配(并务必确保它(在声明数组之前,用于大小的变量具有正确的价值。您没有,并且您脱离了数组的束缚,在堆栈中读取数据。如果这是一个函数,则很可能是从函数退出时会触发运行时错误。
可变长度是此功能的错误称为,因为生成的数组无法更改大小,因此其使用情况非常有限。最好使用STD :: vector,您可以保留提供的尺寸。VLA在C99中允许使用,但不是C 中的标准配置,它们不适合其他C 编译器。
相关文章:
- 算法问题:查找从堆栈中弹出的所有序列
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 为什么调用堆栈数组会导致内存泄漏
- gdb错误:Backtrace已停止:上一帧与此帧相同(堆栈已损坏?)
- 在 leetcode 上提交解决方案时出现堆栈缓冲区溢出错误
- 我的 int main() 中出现堆栈溢出错误
- 堆栈和队列是否像C++中的数组一样传递?
- 拥有映射的现代方法,该映射可以指向或引用已在堆栈上分配的不同类型的数据
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- 从堆栈分配的原始指针构造智能指针
- 在函数范围内在堆栈上分配的数组在离开函数时是否总是被释放?
- 堆栈中大小变量输入错误 (C++)
- 堆栈问题(平衡表达式问题集)
- C++ 在堆栈中包含多态属性的类对象存储
- 用于解析 win64 堆栈跟踪的命令行客户端(可以访问符号服务器)
- 在 C++ 中使用链表进行堆栈
- 变量周围的堆栈'...'已损坏
- 在 gtest 中初始化堆栈上的引用变量的隔离错误
- C++线程的可用堆栈大小