Saverio
Saverio

Reputation: 329

reading a bmp header in C

I wrote a program to read a BMP file header. The code is the following:

#include <stdio.h>

typedef unsigned short WORD;
typedef unsigned short BYTE;
typedef unsigned int DWORD;

typedef struct _WinBMPFileHeader {
  WORD   FileType;
  DWORD  FileSize;
  WORD   Reserved1;
  WORD   Reserved2;
  DWORD  BitmapOffset;
} WINBMPFILEHEADER;

int main(int argc, char* argv[]) {

  WINBMPFILEHEADER *header = NULL;
  FILE *fptr;
  size_t bytes_read;

  if (argc == 2) {
    fptr = fopen(argv[1], "r");
    bytes_read = fread(header, sizeof(WINBMPFILEHEADER), 1, fptr);
  }
  else
    printf("The number of parameters is wrong.\n");

  return 0;

}

When I run the program I have a segmentation fault because of fread. What is the reason of this fault?

Upvotes: 0

Views: 1873

Answers (2)

Dave
Dave

Reputation: 21

try this one, its a sipmle one i use

synHead reader(FILE* img) { 
synHead info;
fseek(img, 10, 0);
fread(&info.D, 1, 4, img);

fseek(img, 18, 0);
fread(&info.W, 1, 4, img);

fseek(img, 22, 0);
fread(&info.H, 1, 4, img);

return(info);

Upvotes: 2

Weather Vane
Weather Vane

Reputation: 34585

Look at this

WINBMPFILEHEADER *header = NULL;
...
bytes_read = fread(header, sizeof(WINBMPFILEHEADER), 1, fptr);

The segmentation fault is because you are passing NULL to the function. You must allocate memory for header, perhaps

header = malloc (sizeof(WINBMPFILEHEADER));

Also you have a declaration error as a separate issue:

typedef unsigned short BYTE;

should be

typedef unsigned char BYTE;

Finally you must make sure you don't have endian issues with any 2 or 4 (I don't think there are any 8) byte fields, a bit off-topic.

Upvotes: 2

Related Questions