开发者社区> 问答> 正文

请教一下这段代码哪里出错了?

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

typedef int Elemtype;
typedef struct node{
  Elemtype elem;
  struct node *next;
}*top;
int m=sizeof(struct node);

struct node *Push(struct node *top,Elemtype x){
  struct node *p;
  p=(struct node *)malloc(m);
  p->next=top;
  top=p;
  p->elem=x;
  return top;
}

struct node *Pop(struct node *top,Elemtype &x){
  if(top==NULL) return 0;
  struct node *p;
  p=top;
  x=p->elem;
  top=top->next;
  delete p;
  return top;
}

Elemtype GetTop(struct node *top){
  if(top==NULL) return -1;
  int x=top->elem;
  return x;
}

int main(){
  struct node *p;
  int x=0,y=0;
  Push(p,2);
  Push(p,34);
  Pop(p,x);
  printf("%d",x);
  y=GetTop(p);
  return 0;
}

然后用g++编译通过,但是运行程序时出现提示:
LinkStack(14073,0x7fff7729d300) malloc: * error for object 0x7fff55c40b00: pointer being freed was not allocated
* set a breakpoint in malloc_error_break to debug
Abort trap: 6

请问这是怎么回事?

展开
收起
a123456678 2016-03-24 10:23:07 1941 0
1 条回答
写回答
取消 提交回答
  •  #include <stdio.h>
    #include <stdlib.h>
    
    typedef int Elemtype;
    typedef struct node{
      Elemtype elem;
      struct node *next;
    };
    
    struct node * top;
    int m=sizeof(struct node);
    
    struct node *Push(Elemtype x){
      struct node *p;
      p=(struct node *)malloc(m);
      p->next=top;
      top=p;
      p->elem=x;
      return top;
    }
    
    struct node *Pop(Elemtype &x){
      if(top==NULL) return 0;
      struct node *p;
      p=top;
      x=p->elem;
      top=top->next;
      delete p;
      return top;
    }
    
    Elemtype GetTop(){
      if(top==NULL) return -1;
      int x=top->elem;
      return x;
    }
    
    int main(){
      top=(struct node *)malloc(sizeof(struct node));
      int x=0,y=0;
      Push(2);
      Push(34);
      Pop(x);
      printf("%d",x);
      y=GetTop();
      return 0;
    }
    2019-07-17 19:12:06
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
《0代码搭应用》 立即下载
不止代码 立即下载
低代码开发师(初级)实战教程 立即下载