0

It's my first time using DDD and i'm pretty inexperienced with the subject matter in question (c in unix environment) so i might be overlooking something. I'm receiving a segmentation fault when i try to fscanf from a file, which doesn't occur in a normal gcc compilation. The function is the following:

void read_config(){
    FILE *fp;
    fp = fopen("config.txt","r");
    fscanf(fp,"TRIAGE=%dDOCTORS=%dSHIFT_LENGTH=%dMQ_MAX=%d ",&data.triage,&data.doctors,&data.shift,&data.mq_max);
}

and after reading the fscanf line it give the following message in DDD:

Program received signal SIGSEGV, Segmentation fault. 0xb7e58e1e in __isoc99_fscanf () from /lib/i386-linux-gnu/lib.so.6

I can't figure out what might be causing this issue. Thanks in advance!

NUGA
  • 185
  • 1
  • 2
  • 8
  • Ensure the input file fits the scanf, and the pointers given as argument fits the types, and that they have enough space to store what has to be stored... Btw i prefer using fgets + strtok – Déjà vu Nov 26 '17 at 15:58
  • Maybe the file doesn't exist in the current directory, or you are not allowed to read it? (errno/perror is your friend) – wildplasser Nov 26 '17 at 16:01
  • @wildplasser the file is in the same directory as the executable and the c file, had i've added `chmod("config.txt", 0644);` to ensure that permissions are in order. Also i added `if(fscanf(fp,"TRIAGE=%dDOCTORS=%dSHIFT_LENGTH=%dMQ_MAX=%d ",&data.triage,&data.doctors,&data.shift,&data.mq_max)==EOF){ perror("Couldn't read from file"); }` – NUGA Nov 26 '17 at 16:27
  • How about `if(!fp)‌​{ perror("Couldn't open file%s", the_file); }` – wildplasser Nov 26 '17 at 16:37
  • @wildplasser sorry for the late response. It printed out no such file in the directory, but the file is there. Maybe i need the file in a different directory because i'm using DDD? – NUGA Nov 26 '17 at 18:15
  • Please see the answer by @Employed Russian . The cwd can be different from the directory where the executable is located. – wildplasser Nov 26 '17 at 18:19
  • @wildplasser yes i've seen it and accepted it as the right answer. Thank you also for taking time to help me on such a rookie issue. – NUGA Nov 26 '17 at 18:28

1 Answers1

0

I can't figure out what might be causing this issue.

Look in the debugger at the value of fp. It will be NULL.

You should always check return value of every system function you call.

the file is in the same directory as the executable

That doesn't matter. What matters is what is your current directory when you are calling fopen.

Unless you instructed DDD to change to the directory where config.txt resides, chances are DDD is running from some other directory.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362
  • Yup that was the problem. Thanks! Pretty embarrassing it was such a rookie mistake but i guess it will never happen again which is good. Thanks again. – NUGA Nov 26 '17 at 18:27