c语言中的堆栈分配空间
我试图根据我的课程笔记实现一个堆栈,但我在编译时遇到了这个错误,不确定我是否正确初始化了它?我的代码在以后使用push功能时出错 更新:我现在看到双重初始化和值被分配到错误的位置 这是我的密码:c语言中的堆栈分配空间,c,stack,C,Stack,我试图根据我的课程笔记实现一个堆栈,但我在编译时遇到了这个错误,不确定我是否正确初始化了它?我的代码在以后使用push功能时出错 更新:我现在看到双重初始化和值被分配到错误的位置 这是我的密码: struct stackelem{ char i; struct stackelem *prev; }; typedef struct stackelem Elem; struct thestack{ Elem *tp; }; typedef struct thestack S
struct stackelem{
char i;
struct stackelem *prev;
};
typedef struct stackelem Elem;
struct thestack{
Elem *tp;
};
typedef struct thestack Stack;
void InitialiseStack(Stack *s)
{
Elem *e = malloc(sizeof(*e));
s->tp = (Elem *)calloc(1, sizeof(Elem));
s->tp->prev = NULL;
}
void Push (Stack *s, int n)
{
Elem *e;
s->tp = (Elem *)calloc(1, sizeof(Elem));
s->tp->prev = s->tp;
s->tp->i = n;
s->tp = e;
}
覆盖tp
,然后尝试使其指向其旧值。除非您在以下时间之前保存,否则无法神奇地发生此情况:
Elem *e = s->tp;
s->tp = (Elem *)calloc(1, sizeof(Elem));
if (s->tp)
{
s->tp->prev = e;
s->tp->i = n;
}
else
{
s->tp = e;
}
现在,如果分配失败,该函数也不会破坏堆栈的状态。这两个函数都没有意义
void InitialiseStack(Stack *s)
{
/* Elem *e = malloc(sizeof(*e)); */
s->tp = (Elem *)calloc(1, sizeof(Elem));
s->tp->prev = NULL;
}
void Push (Stack *s, int n)
{
Elem *e;
s->tp = (Elem *)calloc(1, sizeof(Elem));
s->tp->prev = s->tp;
s->tp->i = n;
s->tp = e;
}
首先在InitialiseStack
中有分配的内存
s->tp = (Elem *)calloc(1, sizeof(Elem));
然后在函数Push中,指针s->tp
的值被覆盖
s->tp = (Elem *)calloc(1, sizeof(Elem));
结果导致内存泄漏。此外,每次调用函数Push
时,指针的值都会被覆盖。同时使用未初始化的指针e
Elem *e;
没有道理
void InitialiseStack(Stack *s)
{
/* Elem *e = malloc(sizeof(*e)); */
s->tp = (Elem *)calloc(1, sizeof(Elem));
s->tp->prev = NULL;
}
void Push (Stack *s, int n)
{
Elem *e;
s->tp = (Elem *)calloc(1, sizeof(Elem));
s->tp->prev = s->tp;
s->tp->i = n;
s->tp = e;
}
您所需要的只是以下内容
void InitialiseStack(Stack *s)
{
s->tp = NULL;
}
及
e
在Push()
中未初始化。你看不出来吗?我总是觉得草签有点让人困惑,我想我的老师在它被覆盖的时候浏览了一下。你能告诉我如何在push函数中初始化“e”吗?
void Push (Stack *s, int n)
{
Elem *e = malloc( sizeof( Elem ) );
if ( e != NULL )
{
e->i = n;
e->prev = s->tp;
s->tp = e;
}
}