简体   繁体   English

程序中途终止

[英]The program terminates halfway

i think terminates after the end of the stud() 我认为在stud()结束后终止

struct stud
{
  int flag;
  char surname[90];
  int semester;
};


int prepush(int *stack,int *head,int *n)
{
 int c,r;
 int *p;
 printf("[1].Add Student\n");
 printf("[2].Add Proffesor\n");
 do
 {
    printf("Pick:");
    scanf("%d",&c); 
    getchar();
 }while(c!=1&&c!=2);
 switch(c)
 {
    case 1:p=stud();break;
    case 2:p=prof();break;
 }
 r=push(stack,&head,&n,p);
 return r;
}

i don't know what to return so i can put it in my stack..adress or what 我不知道要返回什么,所以我可以将其放入堆栈中。

int stud()
{
  struct stud a,*p;
  p=(void *)malloc(sizeof(a));
  p->flag=1;
  printf("Give surname:");
  gets(p->surname);
  printf("\nGive semester:")
  scanf("%d",p->semester);
  return p;
}

this is how i call it r=push(stack,&head,&n,p); 这就是我所说的r = push(stack,&head,&n,p);

int push(int *stack,int *head,int *n,int *p)
{
  if(*head==*n)
    return 0;   
  stack[*head++]=p;
  return 1;
}

i actually want to put into a stack pointers that point to structs 我实际上想将指向结构的指针放入堆栈

The three following lines are a major problem: 以下三行是一个主要问题:

struct stud a,*p;
p=(struct stud *)malloc(sizeof(a));
p=&a;

Here you declare two local variables a and p , allocate memory and make p point to it. 在这里,您声明了两个局部变量ap ,分配了内存并使p指向它。 You the directly afterward reassign p to point to the a variable. 您随后直接重新分配 p指向a变量。 That means you loose the memory you allocated in the previous line, and have a memory leak. 这意味着您丢失了在前一行中分配的内存,并发生了内存泄漏。

What's worse is that you then return this pointer to a local variable, and as you know local variables goes out of scope once the function they were defined in returns. 更糟糕的是,您随后将此指针返回到局部变量,并且您知道,一旦在函数中定义了局部变量,它们就会超出范围。 So what will the pointer then point to? 那么指针将指向什么呢? Using this pointer leads to undefined behavior . 使用此指针会导致未定义的行为

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM