I want to read file in binary mode using fread() into structure members.
following is the code which works perfectly on Turbo C compiler(DOS base) but doesn't work for VC++ 6, it is giving exception at fread() statement.

The input to this file we can give any .bmp file name e.g. abc.bmp

header->bfType 19778
header->bfOffBits 54

//Program Starts here

typedef unsigned int WORD;
typedef unsigned long DWORD;
typedef unsigned char BYTE;

typedef struct tagBITMAPFILEHEADER {
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;

char f1[20];
FILE *in;

void main()

printf("\nEnter input file name: ");
//printf("\nEnter output file name: ");

if ((in=fopen(f1, "rb")) == NULL)
   fprintf(stderr, "Cannot open input file.\n");
      return 1;
      fread(&header->bfType,	sizeof(header->bfType),	1,	in);
      fread(&header->bfSize,	sizeof(header->bfSize),	1,	in);
      fread(&header->bfReserved1,	sizeof(header->bfReserved1),	1,	in);
      fread(&header->bfReserved2,	sizeof(header->bfReserved2),	1,	in);
      fread(&header->bfOffBits,	sizeof(header->bfOffBits),	1,	in);

      printf("\nheader->bfType %u",header->bfType);
      printf("\nheader->bfSize %ld",header->bfSize);
      printf("\nheader->bfReserved1 %u",header->bfReserved1);
      printf("\nheader->bfReserved2 %u",header->bfReserved2);
      printf("\nheader->bfOffBits %ld",header->bfOffBits);


If it worked in Turbo C it was because you were lucky. header is an unallocated pointer. Since it is in global space the pointer's value is initialized to 0 during the program's startup code, which is executed before main() is called.

The program crashes because you need to call malloc() to allocate memory to that pointer before calling fread()

it worked in Turbo C, because Turbo C is riddled with undefined behavior and non-ANSI libraries in standard distribution. It's the AOL of C compilers. In other words, it's a joke. Do yourself a huge favor and quit using it.

anyhow.... if you're intent on keeping "header" declared as pointer, then do exactly what Dragon said. Personally, I don't see why you need it to be a pointer since it's local to main. You could more easily declare "header" directly, and write it without all the pointer mechanisms and memory allocations (which has its own additional dangers).

but either way