Umar Sheikh Salem
Umar Sheikh Salem

Reputation: 57

can't access a place in memory

I'm trying to read a binary file of 32 bytes in C, however I'm keep getting "segmentation fault (code dumped)" when I run my program, it would be great if somebody can help me out by pointing where did I go wrong?. my code is here below:

int main()
{


   char *binary = "/path/to/myfiles/program1.ijvm";
   FILE *fp;
   char buffer[32];

   // Open read-only
   fp = fopen(binary, "rb");

   // Read 128 bytes into buffer
   fread (buffer, sizeof(char), 32, fp);



   return 0;
 }

Upvotes: 1

Views: 167

Answers (3)

Chimera
Chimera

Reputation: 6018

You must check the return result from fopen().

I'm assuming you are getting the segfault in the fread() call because your data file doesn't exist, or couldn't be opened, and you are trying to work on a NULL FILE structure.

See the following safe code:

#include <stdio.h>
#include <stdint.h>

#define SIZE_BUFFER      32

int main()
{
   char *binary = "data.txt";
   FILE *fp = NULL;
   char buffer[SIZE_BUFFER];

   // Open read-only
   fp = fopen(binary, "rb");

   // Read SIZE_BUFFER bytes into buffer
   if( fp )
   {
        printf("Elements read %ld\n", fread (buffer, sizeof(char), SIZE_BUFFER, fp));
        fclose(fp);
   }
   else
   {
        // Use perror() here to show a text description of what failed and why
        perror("Unable to open file: ");
   }
   return 0;
 }

When I execute this code it doesn't crash and will print the number of elements read if the file is opened or it will print "Unable to open file" if the file could not be opened.

As mentioned in the comments you should also close the file being exiting. Another thing you can do is the following:

FILE *fp = fopen(.....);

Instead of declaring and assigning in two separate steps.

Upvotes: 1

ARD
ARD

Reputation: 48

There are two possible reasons

  1. The fopen(3) function failed due to some reason, which means fp is NULL, and then you are trying to use the null-pointer in fread(3). This can crash. @OznOg has already given a subtle hint to look into this direction.
  2. If the fopen call is a success (i.e. fp is non-NULL after calling fopen), the code can still crash because you are reading 32 chars into the variable binary, while binary has been initialized with only 30 chars.

Upvotes: 0

Gerardo Zinno
Gerardo Zinno

Reputation: 1712

It's because of the path. Make sure that "/path/to/myfiles/program1.ijvm" points to an existing file. You should always check the return value of fopen.

\\Open read-only
fp = fopen(binary, "rb");
if(fp==NULL){
    perror("problem opening the file");
    exit(EXIT_FAILURE);
}

Notice also that you are reading 32 bytes in your buffer and not 128 as your comment says.

Upvotes: 1

Related Questions