堆的损坏

azzbcc 2012-10-29 11:26:33

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define ERROR 0
#define OK 1
#define OVERFLOW -2

typedef int Elemtype;

typedef struct{
Elemtype *base[2];
Elemtype *top[2];
}BDStacktype; //双向栈类型


int Init_Stack(BDStacktype &tws,int m)//初始化一个大小为m的双向栈tws
{
tws.base[0]=(Elemtype*)malloc(sizeof(Elemtype));
tws.base[1]=tws.base[0] + m;
tws.top[0]=tws.base[0];
tws.top[1]=tws.base[1];
return OK;
}//Init_Stack

int push(BDStacktype &tws,int i,Elemtype x)//x入栈,i=0表示低端栈,i=1表示高端栈
{
if(tws.top[0]>tws.top[1]) return OVERFLOW;
if(i==0) *tws.top[0]++=x;
else if(i==1) *tws.top[1]--=x;
else return ERROR;
return OK;
}//push


int pop(BDStacktype &tws,int i,Elemtype &x)//x出栈,i=0表示低端栈,i=1表示高端栈
{
if(i==0)
{
if(tws.top[0]==tws.base[0]) return OVERFLOW;
x=*--tws.top[0];
// free(tws.top[0]+1);
}
else if(i==1)
{
if(tws.top[1]==tws.base[1]) return OVERFLOW;
x=*++tws.top[1];
// free(tws.top[1]);
}
else return ERROR;
return OK;
}//pop


void main()
{
Elemtype e;
BDStacktype tws;
Init_Stack(tws,6);
// printf("输入栈中元素");//i=0为低端,i=1为高端。
push(tws, 0, 1);
push(tws, 0, 2);
push(tws, 0, 3);
push(tws, 1, 6);
push(tws, 1, 5);
push(tws, 1, 4);

printf("输出元素:");
pop(tws,0,e);
printf("%d ", e);
pop(tws,0,e);
printf("%d ", e);
pop(tws,0,e);
printf("%d ", e);
pop(tws,1,e);
printf("%d ", e);
pop(tws,1,e);
printf("%d ", e);
pop(tws,1,e);
printf("%d ", e);

printf("\n");
// getchar();
system("PAUSE");
}

Critical error detected c0000374
Windows 已在 test.exe 中触发一个断点。

其原因可能是堆被损坏,这说明 test.exe 中或它所加载的任何 DLL 中有 Bug。

原因也可能是用户在 test.exe 具有焦点时按下了 F12。

输出窗口可能提供了更多诊断信息。

(VC运行完全OK。。。)
...全文
800 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
azzbcc 2012-10-30
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

这个程序主要问题出现在初始化函数
int Init_Stack(BDStacktype &tws,int m)//初始化一个大小为m的双向栈tws
加注释为修改的地方(两处)
C/C++ code

int Init_Stack(BDStacktype &tws,int m)
{
tws.base[0]=(Elemtype*)malloc(m * sizeof(E……
[/Quote]

受教了,多谢!!
慧钦 2012-10-29
  • 打赏
  • 举报
回复
这个程序主要问题出现在初始化函数
int Init_Stack(BDStacktype &tws,int m)//初始化一个大小为m的双向栈tws
加注释为修改的地方(两处)

int Init_Stack(BDStacktype &tws,int m)
{
tws.base[0]=(Elemtype*)malloc(m * sizeof(Elemtype)); // 你原程序只申请了1个空间,要 * m 才行
if (tws.base[0] == NULL)
return -1;
tws.base[1]=tws.base[0] + m-1; // m 个大小,下村0开始,最后一个应该m-1,原程序 + m越界了
tws.top[0]=tws.base[0];
tws.top[1]=tws.base[1];
return OK;
}//Init_Stack

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧