我在代码块上的树程序中使用此函数,它显示在Pop函数中我正在释放树节点的分割错误。分割故障就像程序接收信号SIGSEGV分割一样,我理解这个错误是由于isEmptyStack()
没有返回1(只有0)值而产生的。似乎Pop函数有错误,我需要这方面的帮助,我被困在这里很多天,请帮助我。
//树型节点的栈实现
typedef struct TreeStructure
{
int data;
struct TreeStructure *left;
struct TreeStructure *right;
}Tree;
typedef struct SListNode
{
struct TreeStructure *data;
struct ListNode *next;
}SList;
typedef struct StackList
{
struct ListNode *Node;
}Stack;
Stack *CreationStack()
{
return NULL;
}
int isEmptyStack(Stack *top)
{
return top==NULL;
}
void Push(Stack **top,Tree *data)
{
SList *new,*tmp;
new=malloc(sizeof *new); // Modification here according to comments
new->data=data;
new->next=*top;
*top=new;
}
Tree *Pop(Stack **top)
{
Tree *data;
SList *tmp;
if(isEmptyStack(*top))
{
printf("Underflow") ;return NULL;
}
else
{
tmp=*top;
*top=tmp->next;
data=tmp->data;
if(tmp) // using do not let occur case of the dangling pointer
free(tmp); // Showing fault here only on Debugging
return data;
}
}
这是为了保留级别订单树....的订单打印从左到右,从下到上,
#include<stdlib.h>
typedef struct TreeStructure
{
int data;
struct TreeStructure *left;
struct TreeStructure *right;
}Tree;
typedef struct ListQueue
{
struct ListNode *Rear;
struct ListNode *Front;
}Queue;
typedef struct ListNode
{
struct TreeStructure *node;
struct Listnode *next;
}List;
typedef struct SListNode
{
struct TreeStructure *data;
struct ListNode *next;
}SList;
typedef struct StackList
{
struct ListNode *Node;
}Stack;
void Reverseorder(Tree *Root)
{
Stack *top; Queue *Q;
Tree *tmp;
if(!Root)
return ;
top=CreationStack();
Q=Creation();
Enqueue(Q,Root);
while(!isEmpty(Q))
{
tmp=Dequeue(Q);
Push(&top,tmp);
if(tmp->right)
Enqueue(Q,tmp->right);
if(tmp->left)
Enqueue(Q,tmp->left);
}
while(!isEmptyStack(top)) // Here Empty checker is going into infinite loop
// due to this error occurs
printf("nReverse Element is %d",Pop(&top)->data);
}
当我检查其他函数是否正常工作时,每当我试图增加我的代码时,从那里开始出现问题,请不要混淆其他函数
请在发布之前仔细检查您的代码。这是我第一眼就发现的一件事,很可能还有其他的,因为你根本没有足够的注意把事情做好。
您的功能Push
:
- 有一个未使用的变量
tmp
- 呼叫
malloc
- 使用
typedef
ed指针 - 区分了两种情况,但它们完全相同
似乎data
是pop函数内部的悬空指针。当您释放tmp时,您也释放了data.