Home > database >  Segmentation fault when using fread() function
Segmentation fault when using fread() function

Time:12-10

I have the following struct and array

#define PAGE_SIZE 256

typedef struct frame_attribute {
    
    signed char content[PAGE_SIZE];

} frame;

frame pmemory[64];

I am trying to read 256 bytes into the content array using fread() in the following way,

fread(pmemory[id].content, sizeof(pmemory[id]), PAGE_SIZE, filePointer);

and it is giving me a segmentation fault. I am not sure what is wrong

CodePudding user response:

You are going to read in the variable pmemory[id].content that has the size PAGE_SIZE sizeof(pmemory[id]) * PAGE_SIZE bytes that in fact is not less than PAGE_SIZE * PAGE_SIZE bytes

fread(pmemory[id].content, sizeof(pmemory[id]), PAGE_SIZE, filePointer);

that invokes undefined behavior.

You need to write at least

fread(pmemory[id].content, PAGE_SIZE, 1, filePointer);

or

fread(pmemory[id].content, sizeof( pmemory[id].content ), 1, filePointer);

CodePudding user response:

From man:

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

The  function  fread()  reads nmemb items of data,
each size bytes long, from the stream pointed to by stream,
storing them at the location given by ptr.

I think the problem is that you are using sizeof(pmemory[id]), try changing it to sizeof(signed char).

You want to read PAGE_SIZE items of data to save in a signed char array, so the items must be of signed char size.

  • Related