调用函数时出现分段错误

时间:2021-01-21 18:38:37

标签: c function pointers segmentation-fault structure

我有这个函数,执行一段时间后会出现分段错误,这似乎是由于其中的函数调用引起的。

void dfs(struct node* gptr,int start)
{
    // printf("\ntest 1");
    struct node* temp;
    struct adjListNode* adj;
    int item;
    push(start);
    // printf("\ntest 2::%d",top);
    while(top!=-1)
    {
        // printf("\ntest 3");
        item=pop();
        printf("\n%d",searchVisit(item));
        if(searchVisit(item)==0)  \\searchVisit is the function call which seems to be the problem
        {
            //printf("\ntest 4");
            printf("%d ",item);
            addVisit(item);
            temp=gptr;
            while((temp!=NULL)&&(temp->data!=item))
                temp=temp->link;
            adj=temp->alink;
            while(adj!=NULL)
            {
                //printf("\ntest 5");
                push(adj->data);
                adj=adj->next;
            }
        }
    }
 
}

我在调用 searchVisit 时只打印了两个语句(测试 1、测试 2)。从前一个函数 dfs 调用的函数。


int searchVisit(int i)
{
    struct adjListNode *ptr;
    ptr=visit;
    int flag;
    flag=0;
    do{
    if(ptr->data==i)
    {
        flag=1;
        break;
    }
    ptr=ptr->next; 
    }while(ptr!=NULL);

    return flag;
}

void addVisit(int item)
{
    struct adjListNode *el;
    el->data=item;
    el->next=NULL;
    if(visit==NULL)
        visit=el;
    else
        visit->next=el;
 return;
}

1 个答案:

答案 0 :(得分:0)

这里

  struct adjListNode *el;
  el->data=item;
  el->next=NULL;

您没有为 el 分配任何内存

此外,addVisit 不会正确添加新元素。您的代码只能包含 2 个元素,因为您总是将新元素添加到 visit->next

你需要类似的东西

void addVisit(int item)
{
  struct adjListNode *el;
  el = malloc(sizeof *el);
  if (!el) exit(1);  // Out of memory
  el->data=item;
  el->next=visit;
  visit = el;
}

这将在链表的前面添加新元素。

顺便说一句:使用像 visit 这样的全局变量是个坏主意。将其作为函数参数传递。

相关问题