C 中的动态堆栈 [弹出崩溃]

Dynamic stack in C [pop crash]

我正在编写一个程序,使用动态堆栈将十进制 int 转换为二进制。 它在最后一次弹出时崩溃。 前任。数量:4 输出:10crash

#include <stdio.h>

struct stack {
    struct stack *prev;
    int val;
    struct stack *next;
};
struct stack *first,*cur,*tmp;
struct stack *GETNODE(){
    struct stack *pt = (struct stack *)malloc(sizeof(struct stack));
};
int counter=1;
void push(int val){
    tmp=GETNODE();
    tmp->prev=NULL;
    tmp->val=val;
    tmp->next=NULL;
    if(first==NULL){
        first=tmp;
        cur=first;
    }else{
        tmp->prev=cur;
        cur->next=tmp;
        cur=tmp;
    }
    counter++;
};

int pop(){
    int val=tmp->val;
    cur=tmp->prev;
    free(tmp);
    tmp=cur;
    tmp->next=NULL;
    counter--;
    return(val);
};


main(){
    int num = 4;
    while(num!=0){
        push(num%2);
        num/=2;
    }
    while(counter!=1){
        printf("%d ",pop());
    }
}

问题出在您的 pop 函数中。如果你考虑一下它是如何运作的,在最后一次传递中你将释放 (tmp),它当前指向第一个项目。在你释放它之后,你然后分配:

tmp->next=NULL;

此时您正在尝试解除对无效指针的引用。

我对你的代码做了很多修改。主要是,它太复杂了——只需要一个单链表,你不需要计数器——只需要跟踪列表指针。您的 GETNODE() 函数没有 return 值,导致调用函数出现未定义的行为。我也简化了它,不需要单独的函数来分配内存,因为 malloc() 已经这样做了。

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

struct stack {
    struct stack *prev;
    int val;
};

struct stack *first = NULL;

void push(int val){
    struct stack *pt = malloc(sizeof(struct stack));
    if (pt == NULL){
        printf ("Bad call to malloc()\n");
        exit (1);
    }
    pt->prev=first;
    pt->val=val;
    first = pt;
}

int pop(){
    int val;
    struct stack *pt = first;
    if (first == NULL)
        return -1;
    val=first->val;
    first = first->prev;
    free(pt);
    return(val);
}

void dec2bin(int num){
    printf("%-5d", num);
    while(num!=0){
        push(num%2);
        num/=2;
    }
    while(first){
        printf("%d",pop());
    }
    printf("\n");
}

int main(void){
    dec2bin (4);
    dec2bin (129);
    dec2bin (160);
    return 0;
}

程序输出:

4    100
129  10000001
160  10100000

我更改了您的部分代码,您的代码现在可以正常工作了。

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

struct stack {
     struct stack *prev;
     int val;
     struct stack *next;
};

struct stack *first, *cur, *tmp;
int counter = 0;

struct stack *GETNODE()
{
     return malloc(sizeof(struct stack));
}


void push(int val)
{
    tmp = GETNODE();
    tmp->prev = NULL;
    tmp->val = val;
    tmp->next = NULL;

    if (first == NULL) {
         first = tmp;
         cur = first;
    } else {
         tmp->prev = cur;
         cur->next = tmp;
         cur = tmp;
    }
    counter++;
}

int pop(void)
{
     int val = cur->val;

     tmp = cur;
     cur = cur->prev;
     free(tmp);
     counter--;

     return val;
 }


int main(int argc, char *argv[])
{
    int num;

    scanf("%d", &num);

    while (num != 0) {
        push(num % 2);
        num /= 2;
    }
    while (counter != 0)
    printf("%d ", pop());
    printf("\n");
}