I have come up with a working code for this problem but I spent hours debugging to find out the main issue I had was the order of some variables. Please explain to me why the order matters and why the code works (given everything else stays the same) in this order:

BYTE buffer[512];  

// create outfile
FILE *output = NULL;

// name for jpgfiles 
 char jpgname[7];

but if they are arranged in any order the program does not work and either spits out a few unreadable jpegs or has a segmentation fault.

1 Answer 1


You still have a problem, but don't realize it. The reason that order appears to matter is that the code is overwriting the data in storage that follows jpgname. You have allocated a length of 7 to jpgname to allow for a 7 character filename. But what's going to happen to the end of string makrer \0? In practice, it's going to be written to the physical memory that follows jpgname in storage, overwriting whatever is there. As you saw, if another var is in that position, it gets corrupted. Simply put, the results are going to be unpredictable.

The fix is simple - allocate 8 chars instead of 7 and the order doesn't matter.

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

  • Thank you! I cannot believe how simple that was and it nagged me for hours. I certainly won't forget that again. Code now works with those in any order. Thank you for clearing that up.
    – Hoya Coder
    Commented Mar 4, 2017 at 2:59

You must log in to answer this question.

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