0

I am facing a problem and I tried to debug it but I couldn't find anything

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

struct Process {
    int id;
    int at;
    int bt;
    int rt;
    struct Process *next;
} *tmp;

struct Queue {
    struct Process *head, *tail;
};

struct Process *pop(struct Queue *queue) {
    if (queue->head == NULL) {
        return NULL;
    }
    tmp = queue->head;
    queue->head = queue->head->next;
    return tmp;
}

int main() {
    struct Queue queues[3];
    struct Process *working;
    for (int i = 0; i < 3; i++) {
        queues[i].head = NULL;
    }
    FILE *processesFile = fopen("processes.txt", "r");
    while (!feof(processesFile)) {
        fscanf(processesFile, "%d %d %d", &id, &at, &bt);
        push(&queues[0], id, at, bt);
    }
    working = pop(&queues[0]); // HERE IS THE PROBLEM, It is removing the first element but causing segmentation error
    return 0;
}

I removed the pushing part, I could successfully push 5 values and print the whole queue without any problems

Ambitions
  • 2,369
  • 3
  • 13
  • 24
  • 2
    the problem is probably in the pushing part. For instance, if you don't set the `next` field to NULL when pushing. Can you [edit] your post so we can see it? – Jean-François Fabre Nov 02 '16 at 20:56
  • I don't know if this is the solution, hence a comment. You are using the dreaded `feof` incorrectly. It does not tell you are at end-of-file. Please see [Why is “while ( !feof (file) )” always wrong?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). If you had made essential check of the return value from `fscanf` this error would have been trapped. `if(fscanf(processesFile, "%d %d %d", &id, &at, &bt) != 3) { /* trap error */ };`. The idiomatic way to write the loop is `while(fscanf(processesFile, "%d %d %d", &id, &at, &bt) == 3) { /* process */ }` – Weather Vane Nov 02 '16 at 21:05
  • @Jean-FrançoisFabre I forgot to set "next" to NULL in of the cases. Thank you. – Ambitions Nov 03 '16 at 06:22
  • add to the question the function that does `push` – ThunderWiring Nov 03 '16 at 10:33

1 Answers1

0

I dont see the definition for push(&queues[0], id, at, bt);. fscanf(processesFile, "%d %d %d", &id, &at, &bt); here the variables id,at and bt are used but they are not actually accessed as structure variables.

Darshan b
  • 157
  • 7