Pages

Saturday, June 8, 2019

Not a Good Day

cygwin includes gcc, but the installed version has no idea where stddef.h is (found the fix for that) or what options to pass to ld to link the object to the libraries.  (Found a fix for that, but what else will I find after that?)  FileZilla still says it transferred files to the VM client, but the client does not show them.  Time to reboot Windows.

No change.  So I moved it to my webpage from Windows and back down to Linux.  Now it appears that I have forgotten bsic C, and my hardback edition of Kernighan and Ritchie is gone.  (Found it!)

 Why does this segmentation fault on fgets?

#include
#include
int main (int argc, char *argv[])
{
  FILE* inputFile;
  char* inputString;
 
  inputString = malloc(500);
  inputFile = fopen(argv[1], "r");
  inputString = fgets(inputString, 500, inputFile);
  printf("%s\n", inputString);
  exit(0);
}


I started with char inputLine[500] with same result.  Faults only in the debugger.  gdb works fine; DDD which uses gdb to provide a GUI fails.  I wish ancient releases of debian (the base for linuxcnc) supported modern Eclipse.

Using gdb from the command line takes me back to the 1980s, and reminds me why I helped develop a GUI high-levcl language debugger back then for Kontron Electronics.  I am relearning C, with the inevitable pointer reference problems that led to C++.

4 comments:

  1. You are re-assigning inputString with the result of fgets (which is an int).

    Also, when running from the debugger, did you remember to do a set args filename.txt? The fopen will fail if argv[1] isn't set.

    ReplyDelete
  2. A quick search suggests that the file isn't in the current directory and fopen is returning NULL.

    ReplyDelete
  3. I would check inputFile != null to confirm the file open worked, and not assign inputString = fgets(...); rather just test the return value != null to confirm the fgets successfully copied;

    if (argc < 2) {
    /* print usage string */
    exit(-1);
    }

    inputFile = fopen (argv[1] , "r");
    if (inputFile == NULL) perror ("Error opening file");
    else {
    if ( fgets (inputString, 500 , inputFile) != NULL )
    printf("%s\n", inputString);
    else
    printf("Could not read from file\n");

    fclose (pFile);
    }

    The only thing I see that could cause a seg fault on the fgets line is if the file open failed for some reason.

    ReplyDelete
  4. Thanks for all the help. I am slowly working my way through the real code. char *list[] means to malloc the memory before copying a string into it. The things you forget.

    ReplyDelete