ZoeGreenn 2016-02-29 11:43 采纳率: 0%
浏览 1322

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

 #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

请问这是怎么回事?

  • 写回答

3条回答

  • threenewbee 2016-02-29 11:59
    关注
     #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;
    }
    
    
    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配