2013-06-01 70 views
1

如果我輸入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); 
} 
+0

輸入2在哪裏對不起? – Nobilis

+0

DWORD WINAPI workerThreadProcedure()第3行,當用戶被要求「輸入輸入:」時,輸入2. – Ayse

+0

DWORD WINAPI workerThreadProcedure()第3行,當用戶被要求輸入輸入時, 2. – Ayse

回答

1

我不得不承認這是一個有點難以理解,但我認爲這個問題是在這裏:

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將返回NULL。無論如何,這是錯誤的。

一旦你完成它,你只能釋放內存,跟蹤你的指針指向什麼。不確定你想在這裏做什麼,區分指針和它指向的內容。

指針將在函數結束時過期,它指向的內容不一定(特別是如果它被分配malloc)。

完全可以用幾個指針來指向一件事,當你擺弄那件事時,它會影響所有指向它的指針。

+0

解決問題。非常感謝:) – Ayse

+0

很高興我有幫助:) – Nobilis