0

I'm having trouble finding the error in the following code. It successfully creates 50 jpg files that can be opened and viewed. But it fails check50:

:) recover.c exists
:) recover.c compiles
:) recovers 000.jpg correctly
:( recovers middle files correctly
:( recovers last file correctly
https://sandbox.cs50.net/checks/b9349363100144ccbfa7f023211d3b7e

I'm not sure what went wrong... as 000.jpg and 001.jpg both pass check50 but 002.jpg fails, which is bizarre -- if the loop is problematic, 001.jpg shouldn't've passed.

[code hidden behind link per academic honesty guidelines]

1

It's a subtle error, but repeated several times throughout the program. Look at the following line:

sizeread = fread(buffer, sizeof(buffer), 1, file);

So, in sizeof(buffer), what is buffer? It's a pointer. What's the size of any pointer? 8 bytes. You wanted the size of what is being pointed at, but you got the size of the pointer itself.

The code isn't reading and writing 512 byte blocks, it's reading and writing 8 byte blocks. In the process, it's finding a false signature. There is at least one string of bytes in the middle of an image file that would match a signature. You're finding it, and creating an extra file because of it.

While it is possible to implement this pset successfully with a malloc as you did, these errors are common for this technique.

Credit to @curiouskiwi who spotted the error. ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

2
  • 1
    I'll just add that you can continue to use your malloced block by simply changing your fread (and fwrite) to read/write 512 bytes rather than sizeof(buffer) bytes.
    – curiouskiwi
    May 24 '16 at 1:40
  • Did just that. Thank you so much!
    – Kevin
    May 24 '16 at 1:45

You must log in to answer this question.

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