Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverted arguments in scanf()

I was (quickly) writing some code and accidently inverted the arguments in scanf():

char i[] = "ABC1\t";
scanf(i, "%s");

Compiling with gcc -Werror -Wall -Wextra doesn't complain about this one bit. Obviously, this code doesn't work, but why didn't gcc inform me that I inverted the arguments? Can't it detect that i is not a format string, or that the second argument was not a store-able type?

EDIT
Thanks for the insight all, Looks like I found the answer, there was a twist on the -Wformat flag that makes this "catchable" (posted it below for reference)

like image 809
Mike Avatar asked Oct 25 '12 12:10

Mike


People also ask

When scanf returns 0 in C?

A return value of 0 means that no fields were assigned.

How many arguments can printf take?

Printf can take as many arguments as you want. In the man page you can see a ... at the end, which stands for a var args. If you got 96 times %s in your first argument, you'll have 97 arguments (The first string + the 96 replaced strings ;) )

How does Scanf work in assembly?

sscanf takes as arguments a string to scan, a format string, and pointers to variables where to store the results of the scan. So, your 0 and 1 numbers would be stored on the corresponding variables, assuming the scan was successful. EAX contains the return value.


2 Answers

Ha! I found it. Hitting gcc with the -Wformat=2 flag caught it.

Posting the info for reference of others:

Here's the list of flags I found

-Wformat Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified...

I had assumed -Wall had -Wformat in it, which it does, but the really important part about what I just found:

-Wformat is included in -Wall. For more control over some aspects of format checking, the options -Wformat-y2k, -Wno-format-extra-args, -Wno-format-zero-length, -Wformat-nonliteral, -Wformat-security, and -Wformat=2 are available, but are not included in -Wall.

like image 67
Mike Avatar answered Sep 28 '22 15:09

Mike


I suppose it shouldn't.

int scanf ( const char * format, ... );

i was normally converted to a const char*, all the rest parameters are just "ellipsis" and cannot be checked at compile time.

like image 25
Lyth Avatar answered Sep 28 '22 15:09

Lyth