返回主函数时出现分段故障

Segmentation Fault on return of main function

本文关键字:分段 故障 函数 返回      更新时间:2023-10-16

我已经写了一个代码,这是编译良好,但返回一个运行时错误。在调试代码时,我发现错误是在返回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];

all3*n项,但是您的循环不仅循环到3*n,而且在该循环中增加j 3次。j的值最终将超过为all分配的空间。