在c中实现堆栈时出错

时间:2016-03-04 19:25:56

标签: c

我正在尝试在c中实现stack。这就是我所做的 -

#include <stdio.h>
#include <stdlib.h>

typedef struct stack 
{
    char * data;
    struct stack * next;
}stack;
stack * top1;

void push(char* data,stack * top)
{
    stack* temp;
    temp = (stack*)malloc(sizeof(stack));
    if (!temp)
        return;
    temp->data = data;
    temp->next = top;
    top = temp;
}

int isEmpty(stack * top)
{
    if(top == NULL)
        return 1;
    return 0;
}

char* pop(stack * top)
{
    stack* temp; char*data;
    if (isEmpty(top) == 1)
        return "FALSE";
    temp = top;
    data = top->data;
    top = top->next;
    free(temp);
    return data;
}

void display(stack * top)
{   stack* temp = top;
    while(temp!=NULL) {
        printf("%s \n",temp->data);
        temp = temp->next;
    }
}

 int main()
 {
    top1=(stack *)malloc (sizeof(stack));
    push("aa",top1);
    push("bb",top1);
    push("cc",top1);
    display(top1);
    char* data;
    data =pop(top1);
    printf("Pop = %s\n",data );
    data =pop(top1);
    printf("Pop = %s\n",data );
    display(top1);
 }

但是我收到以下错误 -

(null) 
Pop = (null)
*** Error in `./exe': double free or corruption (fasttop): 0x00000000025cc010 ***
Aborted (core dumped)

代码似乎是正确的,但是它给出了错误。

1 个答案:

答案 0 :(得分:5)

pushpop中,您传递top1。因此,当您在两种情况下操纵局部变量top时,它对top1没有影响。

您需要将top1地址传递给这些函数才能修改其内容。此外,您应该将top1初始化为NULL。

void push(char* data,stack ** top)
{
    stack* temp;
    temp = malloc(sizeof(stack));   // don't cast the return value of malloc
    if (!temp)
        return;
    temp->data = data;
    temp->next = *top;
    *top = temp;
}
...
char* pop(stack ** top)
{
    stack* temp; char*data;
    if (isEmpty(*top) == 1)
        return "FALSE";
    temp = *top;
    data = (*top)->data;
    *top = (*top)->next;
    free(temp);
    return data;
}
...
 int main()
 {
    top1=NULL;
    push("aa",&top1);
    push("bb",&top1);
    push("cc",&top1);
    display(top1);
    char* data;
    data =pop(&top1);
    printf("Pop = %s\n",data );
    data =pop(&top1);
    printf("Pop = %s\n",data );
    display(top1);
 }