Trying to get my recover.c to work.

My program fread's 512 bytes into a buffer on every iteration of a loop.

The buffer is declared as so:

unsigned int* cfbfr = malloc(512);

Then, at the start of every loop I use:

fread(cfbfr, 512, 1, cf);

Where cf is the file pointer to card.raw . At the end of every loop, I free cfbfr then use malloc to get another 512 bytes. Then, the next 512 bytes should be read from cf and stored in 'cfbfr'

Now what I think should be happening is that the first 512 bytes (1 block) are being fread into cfbfr, then the next 512 on the next loop etc and on every loop cfbfr is holding these 512 bytes.

As int's are 4 bytes, cfbfr should point to an array of 512/4=128 ints. Now, we know the jpeg signature is 4 bytes (8 hex digits): 0xffd8ffe0 or 0xffd8ffe1

Therefore, if the signature is present in the first 4 bytes of the block, they should be present in *cfbfr.

Therefore, I use if ((*cfbfr == 0xffd8ffe0) || (*cfbfr == 0xffd8ffe1)) to check for the signature at the start of the loop.

Executing ./recover exits normally, returning 0. But, no jpegs are written. Running in gdb shows that this condition is never evaluated true.

Thought I'd do a run in valgrind to see if that could help, but that shows no nothing helpful (I think), and shows no memory leaks.

Executing xxd card.raw | grep ffd8 shows that the signature bytes are in fact there and appear 16 times, so I don't think card.raw is corrupted. Side note: xxd also shows the first load of bytes to be all 0? (don't know if this is correct or should even matter).

Sorry if I haven't expressed this question quite clearly, not really sure what code I can show you without breaking the honor code, and this is my first time posting :)

Thanks for you help in advance!

1 Answer 1


Your program is not recovering the images because the cs50 appliance or linux in this case uses the little-endian convention to store or read the data. I really don't know very much about this myself, but if you are interested in this topic you can start by reading in the wikipedia.

But long story short, when a variable has more than one byte, the bytes are readed or stored backwards, because of this you need to chek the hexadecimal number with the pairs of digits that represent a byte writed backwards.

As example, when you want to check if the 1st byte is 0xff 2nd is 0xd8 3rd is 0xff and 4th is 0xe0, but to check all bytes at once in a variable you nedd to check for 0xe0ffd8ff notice the pair of digits are writen backwards, same for the ones ended in 0xe1.

  • Thank you! Saved me some headache here.
    – ahmerb
    Commented Mar 14, 2015 at 15:52
  • Backward! That's the problem! A lot of thanks to you!
    – Hao Xuu
    Commented Jul 25, 2015 at 8:19

You must log in to answer this question.

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