Causes of Segmentation Fault

Asked 1 years ago, Updated 1 years ago, 39 views

The code below is a program that stores numbers entered using a bidirectional list in ascending order.

void insert() inserts the element pointing to w before the element pointing to p.
structure data_t*insert_pos(structure data_t*p, structure data_t:*w): Receive the leading element p,
Returns where w should be inserted.
void printasc(struct data_t*p), void printdsc(struct data_t*p)—Receive the leading element p and

#include<stdio.h>
# include <stdlib.h>

structure data_t{
  int num;
  structure data_t*next,*prev;
};

void insert(struct data_t*p, struct data_t*w){
    p->prev->next=w;
    w->prev=p->prev;
    p->prev=w;
    w->next=p;
}

void remove_list(struct data_t*p, int index){
  structure data_t*a;
  inti = 0;
  for(a=p->next;a!=p;a=a->next){
    if(i==index){
      a->next->prev=a->prev;
      a->prev->next=a->next;
      break;
    }
    i+=1;
  }
}


void printall(struct data_t*p){
  structure data_t*a;
  for(a=p->next;a!=p;a=a->next){
  printf("[p:%p, bp:%p, fp:%p, data:%d]\n", a, a->prev, a->next, a->num);
  }
  printf("\n");
}


int main() {
  structure data_t*p, *w, *head;
  int d, count = 0;
  head->next=head;
  head->prev=head;
  printf("State Input\n";
  for(;scanf("%d", &d)!=EOF; count++){
    w=(struct data_t*)malloc(sizeof(struct data_t));
    w->num=d;
    insert(head,w);
  }
  printf("State Remove\n";
  while(scanf("%d", &d)!=EOF){
    if(count<=d){
      printf("List does not have the index number: %d\n", d);
    } else if (count >d) {
      remove_list(head,d);
      count-=1;
    }
  }
  printall(head);
  return 0;
}

c

2022-09-30 21:44

1 Answers

If there are no errors during compilation, you should review the error detection and alert level options.
Or change the working environment.

For Visual Studio Community 2019 C/C++, the first line head->next=head; displays a warning of "Unsinitialized memory 'head' or "Unsinitialized local variable 'head' is used" error.

In other words, it is caused by using the address even though there is no space for head.

It's important to learn and try algorithms, but if you neglect the basics, you'll just stumble in a simple place and take a lot of time.

It is doubtful whether everything is correct or not, and it often changes over time, but
Look for the following articles and read what they say.

Habit to avoid bugs in C language
Habit to avoid bugs in C language:
In my case Technical bugs in the 4th C language
I don't know C language


2022-09-30 21:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.