2 sinat 21595363 sinat_21595363 于 2016.02.29 19:43 提问

请教一下这段代码哪里出错了?
 #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个回答

caozhy
caozhy   Ds   Rxr 2016.02.29 19: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;
}

caozhy
caozhy   Ds   Rxr 2016.02.29 19:59

34Press any key to continue

yixinkewen
yixinkewen   2016.03.01 07:42

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

需要跟新下变量p的值,在调用push、pop 的时候p的值有修改,

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!