gpt4 book ai didi

c++ - 代码显示错误 *** 检测到堆栈粉碎 *** : ./a.out 终止中止(核心转储)

转载 作者:搜寻专家 更新时间:2023-10-31 02:16:44 24 4
gpt4 key购买 nike

此代码运行不正常,并在运行时显示以下错误:

stack smashing detected: ./a.out terminated
Aborted (core dumped)

但是,如果我们用 i, j 声明 temp,它就可以工作。如果我们在 if block 中声明 temp,也会显示错误。如果我们明确声明数组大小,则不会显示错误。我正在使用 GNU 编译器编译我的代码。

#include<iostream>

using namespace std;

int main()
{
int i, j;
int a[] = {3, 2, 4, 1};
int temp;

for(i = 0; i < 4; i++)
{
for(j = 0; j < 4 - i; j++)
{
if(a[j] > a[j + 1])
{
int temp;
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}

for(i = 0; i < 4; i++)
{
cout << a[i] << endl;
}

return 2;
}

最佳答案

您的代码访问a[j+1]。当 j 为 4 时,这将尝试访问越界的 a[4]a 的大小是 4,所以最后一个元素是 a[3]

越界访问数组索引是未定义的行为。它可能有效,也可能无效。

你说当你写这个的时候,你的程序不会崩溃:

int a[]={3,2,4,1};
int temp;

发生这种情况是因为您的程序为 a 保留了内存,并且它在之后立即将 temp 放入内存中。因此,当您尝试更改 a[4] 的值时,您实际上更改了 temp 的值。

当您删除 int temp; 时,您的程序似乎没有将其他变量放置到对应于 a[4] 的内存位置。它崩溃是因为它无法访问该内存位置。

关于c++ - 代码显示错误 *** 检测到堆栈粉碎 *** : ./a.out 终止中止(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36604852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com