关于free()栈的内存的时,无法继续运行问题(求助)

最近学习数据结构,用C语言写了栈的基本操作,却发现在销毁栈时,初始尺寸STACK_INIT_SIZE改成10,1000可以顺利运行,改成100无法运行(编译都没问题),这让我无法理解。下面是代码和运行的结果,希望有懂得朋友能帮助解释下,是代码问题还是其他问题。

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

//STACK_INIT_SIZE改成10,1000可以顺利运行,改成100无法运行!
#define STACK_INIT_SIZE 10 
#define STACK_INCREMENT 10
typedef int ElemType;
typedef int Status;

typedef struct{
    ElemType *base;
    ElemType *top;   //栈顶指向准备存放的位置
    int stackSize;   //当前可以使用的最大容量
}SqStack;

Status initStack(SqStack *s){
    s->base = (ElemType*)malloc(STACK_INIT_SIZE * sizeof(ElemType));
sizeof(SElemType)
    if(!(s->base)){
        return false;
    }
    s->top = s->base;
    s->stackSize = STACK_INIT_SIZE;
    return true;
}

Status push(SqStack *s,ElemType e){
    //如果栈满(s->top - s->base = s->stackSize),追加空间
    if(s->top - s->base >= s->stackSize){
        s->base = (ElemType*)realloc(s->base , (s->stackSize + STACK_INCREMENT) * sizeof(ElemType));
        if(!(s->base)){
            return false;
        }
        s->top = s->base + s->stackSize ;              //设置栈顶
        s->stackSize = s->stackSize + STACK_INCREMENT; //设置栈的最大容量
    }
    //进栈时先存入数据于栈顶,栈顶指针再往后移
    *(s->top) = e;
    s->top ++;

    return true;
}

Status pop(SqStack *s , ElemType *e){
    //栈为空
    if(s->top == s->base){
        return false;
    }
    //出栈时栈顶指针先往前移,再取出栈顶数据
    (s->top)--;
    *e = *(s->top);
    return true;
}

int getCapacity(SqStack *s){
    return s->top - s->base;
}

Status clearStack(SqStack *s){
    s->top = s->base ;
    return true;
}

Status destroyStack(SqStack *s){
    s->top = s->base + s->stackSize;

    while(s->top != s->base){
        free(--s->top);           //运行到这程序停止!
        cout<<*(s->top)<<" ";
    }
    s->top = s->base = NULL;
    s->stackSize = 0;
    cout<<"\n";
    return true;
}

int main(int argc, char *argv[])
{
    SqStack s;
    initStack(&s);
    ElemType e = 1;
    ElemType elm;
    push(&s,e);
    e = 2;
    push(&s,e);
    e = 3;
    push(&s,e);
    e = 4;
    push(&s,e);
    e = 5;
    push(&s,e);
    e = 6;
    push(&s,e);
    pop(&s,&elm);
    cout<<elm<<" ";
    pop(&s,&elm);
    cout<<elm<<" ";
    pop(&s,&elm);
    cout<<elm<<" ";
    pop(&s,&elm);
    cout<<elm<<" ";
    pop(&s,&elm);
    cout<<elm<<"\n";
    cout<<"Capacity:"<<getCapacity(&s)<<"\n";
    clearStack(&s);
    cout<<"Capacity after clear the stack:"<<getCapacity(&s)<<"\n";
    destroyStack(&s);
    //cout<<getCapacity(&s)<<"\n";
    //cout<<clearStack(&s)<<"\n";
    return 0;
}

STACK_INIT_SIZE为10的运行结果,程序正常结束。

STACK_INIT_SIZE为100的运行结果,程序终止。

STACK_INIT_SIZE为1000的运行结果,程序正常结束。

猜你喜欢

转载自blog.csdn.net/XindaBlack/article/details/82527203