bus error?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dn6326
    New Member
    • Sep 2007
    • 6

    bus error?

    can anyone tell me why the following gives me a bus error? Cheers

    void doList(char args[]){
    FILE *file;
    char c;
    List *list = NULL;

    file = fopen(args, "r");
    while(1){
    c = fgetc(file);
    if(c != EOF){
    list = insertList(c, list);
    }
    else{
    break;
    }
    }

    fclose(file);
    }
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by dn6326
    can anyone tell me why the following gives me a bus error? Cheers

    [code=c]
    void doList(char args[]){
    FILE *file;
    char c;
    List *list = NULL;

    file = fopen(args, "r");
    while(1){
    c = fgetc(file);
    if(c != EOF){
    list = insertList(c, list);
    }
    else{
    break;
    }
    }

    fclose(file);
    [/code]
    }
    The EOF value is supposed to be out of the range of normal chars. For unsigned
    chars the EOF value typically is -1. If you assign that value to an unsigned char
    it will be truncated to 255 which definitely isn't equal to -1. Better make variable
    c an int and cast it back to a char when you want to insert it to that list.

    kind regards,

    Jos

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Originally posted by JosAH
      Better make variable
      c an int and cast it back to a char when you want to insert it to that list.
      Better to skip the cast altogether and get your data into an int in the first place. Then when you are sure you haven't got an EOF, then assign the int to a char.

      Comment

      Working...