Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fread a single int from bin file gives me a segmentation fault in C

Tags:

c

fread

I want your help in something that should be easy and I do not know why it does not work. I want to read the first data from a bin which I know that it is an int. I am using the following part of code, but I am getting a segmentation fault:

int main(int argc, char **argv)
    {
        int *data;
        /*opening file*/
        FILE *ptr_myfile;
        ptr_myfile=fopen(myfile.bin","rb");
        if (!ptr_myfile)
        {
            printf("Unable to open file!\n");
            return 1;
        }
        /*input file opened*/
        printf("I will read the first 32-bit number\n");
        /*will read the first 32 bit number*/
        fread(&data,sizeof(int),1, ptr_myfile);
        printf("Data read is: %d\n",*data);     

        fclose(ptr_myfile);
        return 0;
    }

I also tried calling it like this:

fread(data,sizeof(int),1, ptr_myfile);

It should be something with the pointer but I cannot see what.

like image 659
ghostrider Avatar asked Dec 18 '25 19:12

ghostrider


2 Answers

Change:

  • int *data; to int data;
  • printf("Data read is: %d\n",*data); to printf("Data read is: %d\n",data);

You are reading the int into a pointer, then trying to dereference the pointer (which is has a value that's meaningless as a pointer).

like image 50
Michael Burr Avatar answered Dec 20 '25 10:12

Michael Burr


You don't have any memory allocated to data and in the first example code you are not using the pointer correctly. This is an alternative that could work:

int data;

and then you would use it like so:

fread(&data,sizeof(int),1, ptr_myfile);

In your original code, here you are writing an int into a pointer:

fread(&data,sizeof(int),1, ptr_myfile) ;

and then this *data will be dereferencing an invalid pointer. In the alternative case:

fread(data,sizeof(int),1, ptr_myfile);

you will be using a pointer that has no memory allocated to it.

like image 44
Shafik Yaghmour Avatar answered Dec 20 '25 09:12

Shafik Yaghmour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!