Home > Enterprise >  fread segmentation fault reading database from binary file in c
fread segmentation fault reading database from binary file in c

Time:11-24

I am writing a function, that helps me read a database of books from a binary file. However when using fread i am having a segmentation fault.

This is the function I am talking about.

Array *readdb (FILE *db, Array *ind) {
    Array *database = NULL;
    Book *book = NULL;
    indexbook *indentry;
    char *buffer, bytesdepillar = 0, titprintby[MAX_ENTRADA];
    int reader = 0;

    if (db == NULL || ind == NULL) 
        return NULL;

    database = malloc(sizeof(Array));

    initArray(database, INIT_ARR_SIZE);

    fseek(db, 0L, SEEK_END);
    bytesdepillar = ftell(db)/sizeof(char);
    fseek(db, 0, SEEK_SET);
    buffer = malloc(bytesdepillar * sizeof(char));
    fread(buffer, sizeof(char), bytesdepillar, db);
    
    for (size_t i = 0; i < ind->used; i  ) {
        book = malloc(sizeof(Book));
        indentry = (indexbook*) ind->array[i];

        reader = indentry->offset;

        book->bookID = indentry->key;
        reader =sizeof(int);
        memcpy(book->ISBN, &buffer[reader], ISBN_LEN);
        reader =ISBN_LEN;
        memcpy(titprintby, &buffer[reader], indentry->offset   indentry->size - reader);
        strcpy(book->title, strtok(titprintby, "|"));
        strcpy(book->printedBy, strtok(NULL, "|"));
    
        insertArray(database, book);
    }

    return database;
}

ind is the database index with the following structure:

typedef struct {
  int key;
  long int offset;
  size_t size; 
} indexbook;

The file is being opened with

    if ((dbf = fopen(db_name, "rb")) == NULL) {
        fclose(indf);
        printf("%s does not exist", db_name);
        return 1;
    }

CodePudding user response:

As you have stated in the comments section, when the line

fread(buffer, sizeof(char), bytesdepillar, db);

is executed, the variable bytesdepillar has a negative value.

Since you declared the variable to be of type char, depending on your platform, it is probably only able to represent values between -128 and 127. If the call to ftell returns a value that is higher than 127, it will probably (it is implementation-defined what exactly happens) be converted to a value between -128 and 127. That is most likely the reason why it is a negative value.

Therefore, I recommend that you change the declared type of bytesdepillar from char to long, which is the type returned by the function ftell.

If, after changing the declared type to long, the value continues to be negative, then it is probably due to the function ftell returning -1 due to the function failing. In that case, you should verify that db refers to a valid stream (e.g. verify that the file that has been successfully opened).

  •  Tags:  
  • c
  • Related