Segment fault! Need help
May 23, 2019 at 11:38am UTC
I receive the Segment fault (core dumped) error when I build the small queue by using pointer below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include <stdio.h>
#include <stdlib.h>
struct data {
int pid;
struct data *next;
};
struct data1 {
struct data *head;
struct data *tail;
};
void initial_data(struct data * tes){
tes->pid = 5;
tes->next = NULL;
}
int empty(struct data1 *q){
return (q->head == NULL);
}
struct data * de_queue(struct data1 * q) {
struct data * proc;
if (empty(q)){
proc = NULL;
}
else {
proc = q->head;
q->head = q->head->next;
}
// YOUR CODE HERE
return proc;
}
void en_queue(struct data1 * q, struct data * proc) {
printf("%d\n" , proc->pid); // here it prints
if (empty(q)){
printf("%d\n" , proc->pid); // from here it does not print
q->head = proc;
q->tail = proc;
}
else {
q->tail->next = proc;
q->tail = q->tail->next;
}
}
int main(){
struct data1 queue;
struct data tes;
initial_data(&tes);
en_queue(&queue, &tes);
}
May 23, 2019 at 11:44am UTC
You never set head
or tail
to null, hence empty(...) will probably never return 1 and the data is inserted at an invalid position.
May 23, 2019 at 11:47am UTC
Use your debugger to step through the program. You'll be able to see exactly where it's crashing, and to examine the contents of the memory to see why it's crashing.
HINT: What value q->head
to have at line 36?
May 23, 2019 at 11:53am UTC
thank both you! I did not recognize those
May 23, 2019 at 1:24pm UTC
You're welcome!
Although my advice still stands: learn to use your debugger, so that you can investigate and fix these kinds of bugs yourself .
Topic archived. No new replies allowed.