1

enter image description here

As you can see, the if statement on the line 35 is false. Why is the body of the if statement being executed?

1

The statement is actually true. The issue here is how the values are being displayed, and the clue is to look at the pattern of your if statement:

if ((buffer[0] == 255 && buffer[1] == 216 && buffer[2] == 255 && buffer[3] == 224) ||
    (buffer[0] == 255 && buffer[1] == 216 && buffer[2] == 255 && buffer[3] == 255))

If we look only at where the numbers are similar and where they are different, the pattern you are checking for in the first four characters of the buffer is A B A C or A B A A. Now, what is the pattern in the characters you see in gdb?

$2 = "\377\330\377\340\000\020\JFIF\000...

The first four characters are \377\330\377\340, which matches the pattern A B A C. That's your first clue - you can figure it out yourself, but here are some hints before I give you the solution.

Hint #1:

What are the different printf specifiers for displaying numeric values?

Hint #2:

Can you figure out a way to write 255, 216 and 224 as "\377", "\330" and "\340"? Try subtracting to see how far apart the values are.

Hint #3:

Google "c 255 377"

If you went through the hints you have surely figured it out by now, but if you were too impatient, here's the answer:

The values are being printed out in octal representation, also known as base-8. Unlike hexadecimal, which includes the letters a-f, octal can look a lot like regular old decimal (base-10) notation. But when you see the \ escape character, you should think aha! That's not just a number or a character, it's some kind of code. Then you just have to figure out what the code is.

By the way, you could write that same if statement a little more compactly and efficiently, since it's testing the same exact thing for the first three characters. Like this:

if (buffer[0] == 255 && buffer[1] == 216 && buffer[2] == 255 && (buffer[3] == 224 || buffer[3] == 255))

This way, as soon as any of the first, second or third characters don't match, you know the entire statement fails without testing the remaining characters. In your original code, if any of the characters don't match the first part of the OR statement, you have to check all four characters again in the second part of the OR statement, even the ones you already checked.

1

You must log in to answer this question.

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