如果输入2作为输入,则输出为-572662307。
有人能找出问题吗?
struct node
{
int rollno;
struct node*n;
};
void read(struct node*);
void display(struct node*);
struct node* create();
struct node* cread();
struct node*head=NULL;
struct node*tail=NULL;
void read(struct node*p)
{
scanf("%d",&p->rollno);
p->n=NULL;
printf("\n");
}
void display(struct node*p)
{
printf("%d\n",p->rollno);
}
struct node* create()
{
struct node*q;
q=(struct node*)malloc(sizeof(struct node));
return q;
}
struct node* cread()
{
struct node*j;
j=create();
read(j);
return j;
}
void push(struct node*cur)
{
if(head==NULL)
{
head = cur;
tail = cur;
}
else
{
struct node*f;
f=head;
head->n = cur;
head=head->n;
}
}
struct node* pop()
{
struct node*p;
struct node*s = NULL;
p=tail;
if(p==NULL)
{printf("\n\t\t\tSTACK EMPTY\n");}
else
{
//display(p);
s = p;
tail=p->n;
free(p);
}
return s;
}
DWORD WINAPI workerThreadProcedure(LPVOID lparam)
{
struct node* cur;
struct node* disp = NULL;
printf("Enter the input: ");
cur =cread();
push(cur);
disp = pop();
printf("%d\n",disp->rollno);
return 0;
}
void main()
{
HANDLE workerThreadHandle[40];
int max_number=40;
for (int i = 0; i < 1; i++)
{
workerThreadHandle[i]= CreateThread( NULL,
0,
workerThreadProcedure,
(LPVOID)i,
0,
NULL
);
}
Sleep(5000);
}
最佳答案
我不得不承认这有点难理解,但我认为问题在于:
struct node* pop()
{
struct node*p;
struct node*s = NULL;
p=tail;
if(p==NULL)
{printf("\n\t\t\tSTACK EMPTY\n");} // after that will jump to 'return' where 's' is NULL
else
{
//display(p);
s = p; // 's' and 'p' point to the same memory block now
tail=p->n;
free(p); // Ooops you've freed the memory block 's' and 'p' point to
}
return s; // You now return a freed memory block, this is undefined behavior
}
如果只输入
if
语句,则返回s
。无论如何都是错的。你只有在完成后才能释放记忆,记住你的指针指向什么。不确定您想在这里做什么,区分指针和它指向的对象。
指针将在函数的末尾过期,它指向的不一定会过期(特别是如果它是用malloc分配的)。
多个指针指向一个对象是完全可以的,当你摆弄那个对象时,它会影响指向它的所有指针。
关于c - 队列弹出一些垃圾值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16869719/