C [pop crash]中的动态堆栈

时间:2015-02-07 18:14:22

标签: c dynamic stack pop

我正在制作一个程序,使用动态堆栈将十进制int转换为二进制。 它崩溃了最后一个流行音乐。 恩。 num: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());
    }
}

3 个答案:

答案 0 :(得分:1)

问题在于你的pop功能。如果你考虑它是如何运作的,你将在最后一遍中释放(tmp),这是当前指向第一个项目。释放后,您可以指定:

tmp->next=NULL;

此时您正尝试取消引用无效指针。

答案 1 :(得分:0)

我对您的代码进行了很多更改。主要是,它太复杂了 - 只需要一个单链表,你不需要一个计数器 - 只需跟踪列表指针。您的GETNODE()函数未返回值,导致调用函数中出现未定义的行为。我也简化了这一点,不需要单独的函数来分配内存,因为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

答案 2 :(得分:0)

我现在更改了部分代码和代码。

 #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");
}