源码如下:
#include<stdio.h>
#include<string.h>
#include<stdlib.h> //malloc所在库
#define MAXSIZE 100 //宏定义不能加“;”,初始化栈的大小
//const int MAXSIZE = 100;
typedef int SElemType;
typedef bool Status; //状态参数
typedef struct{ //栈结构体
SElemType data[MAXSIZE];
int top; //栈指针
}SqStack;
Status Push(SqStack *S, SElemType e){ //压栈函数
if(S->top == MAXSIZE - 1) //如果已经是满栈,状态返回false
return false;
S->top++; //栈指针+1
S->data[S->top] = e; //压栈
return true; //返回创建成功
}
int main(){
SqStack *S = (SqStack *)malloc(sizeof(SqStack)); //申请内存空间
//S -> top = -1; //应该对top进行初始化,否则报错
SElemType e = 5; //创建待压栈元素e
Push(S, e); //调用压栈函数
free(S); //释放内存
return 0;
}
引起的原因是S->top未初始化,添加初始化赋值:S -> top = -1;
#include<stdio.h>
#include<string.h>
#include<stdlib.h> //malloc所在库
#define MAXSIZE 100 //宏定义不能加“;”,初始化栈的大小
//const int MAXSIZE = 100;
typedef int SElemType;
typedef bool Status; //状态参数
typedef struct{ //栈结构体
SElemType data[MAXSIZE];
int top; //栈指针
}SqStack;
Status Push(SqStack *S, SElemType e){ //压栈函数
if(S->top == MAXSIZE - 1) //如果已经是满栈,状态返回false
return false;
S->top++; //栈指针+1
S->data[S->top] = e; //压栈
return true; //返回创建成功
}
int main(){
SqStack *S = (SqStack *)malloc(sizeof(SqStack)); //申请内存空间
S -> top = -1; //应该对top进行初始化,否则报错
SElemType e = 5; //创建待压栈元素e
Push(S, e); //调用压栈函数
free(S); //释放内存
return 0;
}
出现错误的原因:读取了本该没有的值或者地址。
解决方法主要从以下三个方面出发:
1、检查下传入的参数是否合法;
2、若malloc了一块内存,必须记得free;
3、是否赋值了已经溢出的值或地址。
参考文献:Unhandled exception at 0x… in XXXX.exe: 0xC0000005:Access violation reading location 0x…