0

I'm attempting recover.c and I'm interested in clearing up a few things about fread() and malloc().

I tried to sample the first few bytes of the card.raw file but I keep getting the same two errors: Segmentation Fault 11, or the data I read from the file prints as either 0 or some seemingly random number.

Given the small snippet below, can someone walk me through the correct way to fread() into allocated memory then write that data to either a FILE * or STDOUT?

// debug - write a few bytes from the raw file to the logfile
uint32_t *pattern = malloc(sizeof(uint32_t));
fread(pattern, sizeof(uint32_t), 1, card);
fprintf(logfile, "%x\n", *pattern);
free(pattern);
1

fread() reads the contents of a file (in your case 'card' is the pointer to the file to be read from) and places the contents into a buffer (in your case 'pattern'). The number of bytes placed into the buffer from one read is determined by the second and third parameters.

Every time you call read it will read sizeof(uint32_t) * 1 bytes from the file pointed to by 'card' into the buffer(pattern). The card pointer will then be moved to point to the next byte in the file that has not been read.

You can now write the content from the buffer into a file.

fwrite(pattern, sizeof(uint32_t), 1, logfile);

Here you are writing sizeof(unit32_t) * 1 bytes from your buffer 'pattern' to logfile. Just like the pointer 'card', the FILE pointer logfile will move to the next byte that has not been written, ready for you to call another fwrite().

You can call fread followed by fwrite until you reach the end of the file. A common cause for seg errors is not checking for end of file before reading more bytes from the file. You can check end of file be calling feof().

if(feof(card)) {
    break;
}

You can check if end of file has been reached after each loop iteration. Also make sure a file exists before attempting to open it for reading. If the file doesn't exists it can also cause a seg fault.

4
  • When you say I have to check for the EOF or I'll suffer seg fault, how would you implement that check? Say I've been reading a file for a while and I now have 2 bytes of file left, but I've been reading 4 bytes at a time. In what way can I read those last two bytes without a seg fault if my buffer is 4 bytes wide? May 17 '17 at 18:09
  • en.cppreference.com/w/c/io/fread You can have a read here for more details, but fread will read as many bytes as it can up to the bytes in your buffer. If you have two bytes of file left it will read those in and then the indicator for feof will be triggered and then you can test it. May 17 '17 at 18:30
  • So reading only a partial number of your bytes into the buffer is okay, it is attempting to carry on after this that can cause problems. May 17 '17 at 18:41
  • Thank you so much! ; ) May 17 '17 at 19:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .