1

Here is a simpe program that stores struct into binary file

The struct and item in it

typedef struct Item
{
    int busy; //item is busy
    int key;  //item key
    int len; // len of info in item
    int release;  //item release (version of item)
    char *info;  //info (char array) 
}Item;

typedef struct Table
{
    Item* items[MAX];
    int size = MAX;
}Table;

Here is the code that implements file read and write functionality

// Write table to file
void WriteToFile(const char *filename, Table* table)
{
    FILE *fl;
    Item *p;
    fl = fopen(filename, "w+b");

    fwrite(&(table->size), sizeof(int), 1, fl);

    for (int i = 0; i < table->size; i++)
    {
        p = table->items[i];
        if (p->busy != 0) //Write only elements with busy != 0
        {
            fwrite(&(p->key), sizeof(int), 1, fl);
            fwrite(&(p->release), sizeof(int), 1, fl);
            fwrite(&(p->len), sizeof(int), 1, fl);
            fwrite(&(p->info), sizeof(char), p->len, fl); //p->len contains strlen(info)
        }

    }
    fclose(fl);
}

// Read table from binary file
int ReadFromFile(const char *filename, Table* table)
{
    FILE *fl;
    char *info;
    int key = NULL;
    int release = NULL, len;
    fl = fopen(filename, "r+b");

    if (fread(&table->size, sizeof(int), 1, fl) != 1) return 0;
    while (!feof(fl))
    {
        if (fread(&key, sizeof(int), 1, fl) != 1) return 1;
        if (fread(&release, sizeof(int), 1, fl) != 1) return 0;
        if (fread(&len, sizeof(int), 1, fl) != 1) return 0;
        info = (char *)malloc(len);
        if (fread(&info, sizeof(char), len, fl) != len) return 0;
        //Code that inserts item to table
    }
    fclose(fl);
    return 1;
}

If i try to look info variable under debugger when reading it from file I've got a message "Error reading characters of string". On exit from ReadFromFile function i'm getting an error "Stack around the variable 'info' was corrupted."

Sneftel
  • 40,271
  • 12
  • 71
  • 104
Anton
  • 1,010
  • 10
  • 30
  • Please see [Why is “while ( !feof (file) )” always wrong?](http://stackoverflow.com/q/5431941/2173917) – Sourav Ghosh Apr 22 '17 at 16:34
  • 1
    `fread(&info, ...)` ==> `fread(info, ...)` will perhaps cure the stack corruption. `info` is already a pointer to memory, and you must not try to overwrite the pointer itself. – Weather Vane Apr 22 '17 at 16:34
  • Note that you write a pointer to the file; you need to write that data instead. Look up serialization. – Jonathan Leffler Apr 22 '17 at 16:41

1 Answers1

0

fread requires the first argument to be the first address fom where you are going to start reading. So you need to write

fread(info, sizeof(char), len, f1);

What you have written causes the input to be done in the stack starting from the location where

info

is stored. Since it is a pointer variable itself, it will also occupy 4 bytes on the stack, where the fread operation will happen.

Parth K
  • 587
  • 5
  • 18