返回主函数时出现分段故障
Segmentation Fault on return of main function
我已经写了一个代码,这是编译良好,但返回一个运行时错误。在调试代码时,我发现错误是在返回0语句之后从main函数返回。就我搜索的内容而言,我知道这是一个堆栈缓冲区溢出问题,但无法知道如何纠正。代码可在这里获得http://ideone.com/7ujF4D
#include<iostream>
#include<algorithm>
using namespace std;
struct box{
int h;
int w;
int l;
};
bool mycomp(const box &b1, const box &b2)
{
return((b1.l*b1.w)>(b2.l*b2.w));
}
int boxstack(box b[4], int n)
{
box * all = new box[3*n];
//box *all = (box *)malloc(sizeof(box));
int j = 0;
//cout<<"here";
int * msh = new int[3*n];
//int* msh = (int*)malloc(sizeof(int));
//cout<<"now here";
for(int i=0; i<3*n; i++)
{
all[j].h = b[i].h;
all[j].w = min(b[i].w,b[i].l);
all[j].l = max(b[i].w, b[i].l);
j++;
all[j].h = b[i].l;
all[j].w = min(b[i].w,b[i].h);
all[j].l = max(b[i].w, b[i].h);
j++;
all[j].h = b[i].w;
all[j].w = min(b[i].l,b[i].h);
all[j].l = max(b[i].l, b[i].h);
j++;
}
sort(b, b+3*n, mycomp);
for(int i=0; i<3*n; i++)
{
int maxh = 0;
for(int j=0; j<i; j++)
{
if(all[j].w>all[i].w&&all[j].l >all[i].l)
{
if(maxh<msh[j])
{
maxh = msh[j];
}
}
}
msh[i]=maxh + all[i].h;
}
int maxval = 0;
for(int i=0; i<3*n; i++)
{
if(msh[i]>maxval)
{
maxval = msh[i];
}
}
//delete []all;
//delete []msh;
cout<<"Here";
return maxval;
}
int main()
{
box b[4];
b[0].h=4;
b[0].l=6;
b[0].w=7;
b[1].h=1;
b[1].l=2;
b[1].w=3;
b[2].h=4;
b[2].l=5;
b[2].w=6;
b[3].h=10;
b[3].l=12;
b[3].w=32;
cout<<boxstack(b,4);
cout<<"Hello";
return 0;
}
看看这里的循环:
for(int i=0; i<3*n; i++)
{
all[j].h = b[i].h;
all[j].w = min(b[i].w,b[i].l);
all[j].l = max(b[i].w, b[i].l);
j++; // increment
all[j].h = b[i].l;
all[j].w = min(b[i].w,b[i].h);
all[j].l = max(b[i].w, b[i].h);
j++; // increment again
all[j].h = b[i].w;
all[j].w = min(b[i].l,b[i].h);
all[j].l = max(b[i].l, b[i].h);
j++; // increment once again
}
查看循环前的分配情况:
box * all = new box[3*n];
int j = 0;
int * msh = new int[3*n];
all
有3*n
项,但是您的循环不仅循环到3*n
,而且在该循环中增加j
3次。j
的值最终将超过为all
分配的空间。
相关文章:
- 分段故障(堆芯转储)矢量
- 数组的指针从不分段故障
- Windows 10-使用gtkmm-3.0库和g++[包括再现]的分段故障
- 分段故障 运行C++代码时出现 SIGSEGV
- 分段故障背包问题
- 分段故障 11,从类函数显示动态 C 字符串
- 面临分段故障 使用 ffmpeg 读取视频时,因为"pFormatCtx-> streams [i]-> codecpar"的地址0x00
- 在C++中,当指向删除和指向不同对象时,分段故障指针
- 分段故障说明
- 分段故障(核心转储)-不知道为什么
- 分段故障线程
- hiredis SET遇到分段故障
- 分段故障,合并排序算法
- 多线程程序中的分段故障和gdb回溯上的不完整信息
- 到达主C++之前分段故障
- 分段故障核心使用 IF流转储
- 使用向量的移动键盘排列(分段故障)
- 在二进制树插入和遍历期间,我得到了分段故障
- 分段故障在类之间返回整数
- C++分段故障BST