2017-03-23 67 views
0

这是队列的C程序。我刚刚写入它的插入值。我得到的问题是每次插入第一个元素时出现分段错误。为什么这个程序在这个队列程序中给出了分段错误

#include <stdio.h> 
#include <malloc.h> 
struct node{ 
     int data; 
    struct node *next; 
}; 

struct queue { 
    struct node *front; 
    struct node *rear; 
}; 

struct queue *q; 

void create_queue(struct queue *); 
struct queue *insert(struct queue *,int); 

int main() 
{ 

int val, option; 
create_queue(q); 

do 
{ 

printf("\n *****MAIN MENU*****");  
printf("\n 1. INSERT");  
printf("\n Enter your option : "); 
scanf("%d", &option); 

switch(option) 
     { 
      case 1:    
           printf("\n Enter the number to insert in the queue:"); 
       scanf("%d", &val); 
       q = insert(q,val); 
       break; 

     } 

}while(option != 5); 

return 0; 
} 

void create_queue(struct queue *q) 
{ 
    q = (struct queue *)malloc(sizeof(struct queue)); 
    q->rear = NULL;//how this happened without any error?? 
    q->front = NULL; 
} 

struct queue *insert(struct queue *q,int val) 
{ 

struct node *ptr; 

ptr = (struct node*)malloc(sizeof(struct node)); 
if(ptr == NULL) 
{ 
    printf("error in allocating\n"); 
    return -1; 
} 
    ptr->data = val; 
    if(q->front == NULL) 
    { 
     q->front = ptr;//here I get segmentation fault 
     q->rear = ptr; 
     q->front->next = q->rear->next = NULL; 
    } 
    else 
    { 
     q->rear->next = ptr; 
     q->rear = ptr; 
     q->rear->next = NULL; 
    } 

return q; 
} 

我的程序有什么问题? 为什么分配一个新节点不起作用,当前的语法是什么?

+4

'create_queue()'使所有本地更改..... –

+0

q是一个指针在这里。所以对其元素的任何更改都将被保存。不是吗? – acidlategamer

+0

在'create_queue'中分配的内存不会返回到任何地方,因此您在未分配时使用q导致未定义的行为。用调试器逐行执行会很容易地显示出来。要么返回指针,要么使用** ** –

回答

1

这里的问题是,当您使用全局变量调用函数并接受函数参数中的函数参数时,函数参数将成为被调用函数的本地函数。

这样,局部变量会隐藏全局变量,并且由于C为函数参数传递使用了传递值,因此对本地副本所做的任何更改都不会反映给调用方。

最后,全局指针p保持未初始化。尝试解除引用undefined behavior

你要么

  • 并不需要通过全球(S)作为参数
  • 传递指针的地址和内部功能相同的操作。

那就是说,please see this discussion on why not to cast the return value of malloc() and family in C.

+0

是的程序工作,如果我在调用create_queue(q)之前做malloc的话, – acidlategamer

+1

@acidlategamer这样你避免阴影问题。 :) –

相关问题