讨论/综合讨论/为什么会有内存非法访问呢,因该如何修改/
为什么会有内存非法访问呢,因该如何修改

#include<stdlib.h>
typedef struct {
int *max;
int top;
int *p;
int maxp;
int maxn;
} MaxStack;
MaxStack
maxStackCreate() {
MaxStack s;
int a12[50000],b12[500000],c12[500000];
s=(MaxStack
)malloc(sizeof(MaxStack));

if(s==NULL)
{
    
}
s->p=a12;
s->max=b12;
s->maxp=c12;
s->top=0;
s->maxn=0;
return s;

}
void maxStackPush(MaxStack* obj, int x) {
int max,a,b;
if(obj->maxn==0)
{
obj->top++;
obj->p[obj->top]=x;
obj->maxn++;
obj->max[obj->maxn]=x;
obj->maxp[obj->maxn]=obj->p[obj->top];
}
else
{
obj->top++;
obj->p[obj->top]=x;
if(x>=obj->max[obj->maxn])
{
//obj->maxp[obj->maxn]=obj->top;
//obj->max[obj->maxn]=obj->p[obj->top];
obj->maxn++;
obj->max[obj->maxn]=x;
obj->maxp[obj->maxn]=obj->p[obj->top];
}
else
{
a=obj->max[obj->maxn];
b=obj->maxp[obj->maxn];
obj->maxn++;
obj->max[obj->maxn]=a;
obj->maxp[obj->maxn]=b;
}

}
}
int maxStackPop(MaxStack* obj) {
int a;
if(obj->maxn==0)
{
return 0;
}
else
{
a=obj->p[obj->top];
obj->top--;
obj->maxn--;
return a;
}
}
int maxStackTop(MaxStack* obj) {
if(obj->maxn==0)
{
return 0;
}
else
{
return obj->p[obj->top];
}
}
int maxStackPeekMax(MaxStack* obj) {
if(obj->maxn==0)
{
return 0;
}
else
{
return obj->max[obj->maxn];
}
}
int maxStackPopMax(MaxStack* obj) {
int a,b,i;
if(obj->maxn==0)

{
return 0;
}
else
{
a=obj->max[obj->maxn];
b=obj->top;
i=obj->maxp[obj->maxn];
while(i<=b-1)
{
obj->p=obj->p[++i];
}
--obj->top;
--obj->maxn;
return a;
}
}
void maxStackFree(MaxStack* obj) {
if(obj->maxn!=0)
{
free(obj->max);
free(obj->maxp);
free(obj->p);
}
}

=================================================================
==29==ERROR: AddressSanitizer: attempting free on address which was not malloc()-ed: 0x7ffcbd33f430 in thread T0
#0 0x7fbf5e878f30 in free (/usr/local/lib64/libasan.so.5+0xe7f30)
#4 0x7fbf5cfca2e0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x202e0)

Address 0x7ffcbd33f430 is located in stack of thread T0
SUMMARY: AddressSanitizer: bad-free (/usr/local/lib64/libasan.so.5+0xe7f30) in free
==29==ABORTING

展开讨论
zhangyiming发起于 2019-09-23
共 1 个讨论

MaxStack s;
应该是
MaxStack MaxStack *s吧,下面初始化类型强转也是