alo129
alo129

Reputation: 23

Reading data from file into a struct (C)

Sorry if this formatting is messy this is my first time using stackoverflow. I am trying to use the fread function to read into the card.raw file in blocks of 512 bytes and store the first 4 bytes of the block into s1-s4 and the other 508 bytes left over into the array of bytes. However, when I try to run this I get a segmentation fault. When I tried debugging, after the fread function is called, argv, outptr, inptr, and buf values all become NULL. Why is that and what am I doing wrong?

typedef uint8_t  BYTE;

//block of 512 bytes
typedef struct 
{
    BYTE s1;
    BYTE s2;
    BYTE s3;
    BYTE s4;
    BYTE image[508];
}
BUFFER;

int main(int argc, char* argv[])
{
    //opens memory card file
    FILE* inptr = fopen("card.raw", "r");

    int jpgcounter = 0;

    //creates jpg file
    char title[7];
    sprintf(title, "%d.jpg", jpgcounter);
    FILE* outptr = fopen(title, "a");

    //create buf (pointer) of type BUFFER
    BUFFER* buf;

    do
    {
        //creates buffer structure for storage of 512B blocks 
        buf = malloc(sizeof(BUFFER));

        //read 512 bytes at a time & stores every 512B block into a buffer struct buf
        fread(&buf, sizeof(BUFFER), 1, inptr);

        if(buf->s1 == 0xff && buf->s2 == 0xd8 && buf->s3 == 0xff)
        {

The if statement is used to check if the first 3 elements of buf contain the following hexadecimal signatures. I wanted to use malloc in a loop in order to read the raw file in structs of 512 bytes, decide what to do with the 512 bytes, then free it continuously.

Upvotes: 2

Views: 2312

Answers (2)

Ari0nhh
Ari0nhh

Reputation: 5920

When you pass &buf pointer instead of buf into the fread function it will write your data not in the allocated heap buffer, but on your function stack. Since stack on x86 platforms grows towards the lower memory addresses, this will overwrite everything on the stack, that was before your buf variable - in your case a local variables, function arguments argc, argv, etc and return address. Stack became corrupted and you get a segmentation fault.

Upvotes: 0

Ashwani
Ashwani

Reputation: 104

use fread(buf, sizeof(BUFFER), 1, inptr); instead of fread(&buf, sizeof(BUFFER), 1, inptr); Also open file in binary mode to read i.e. "rb" instead of "r"

Upvotes: 2

Related Questions