how could computer knows how many arguments will be followed?
how could computer knows how many arguments will be followed?
we put the arguments in reverse order
b开发者_JAVA技巧ecause there is sort of printf function
which takes undefined number of arguments.
in case of pritnf, computer could know how many arguments will be followed.
if format string contains "%s, hello, welcome to %s", then just read 2 more arguments.
but how could computer knows when it comes to
such a function which prototype looks like
int func(int a, int b, ...)?
could somebody explain me in assembly level?
thanks
It doesn't. You can printf("%d")
, it will simply print whatever it finds on the stack. You (the programmer) should know how many arguments a function need, both when calling and writing it. If you are not sure, you can write functions which have as first argument the number of the other arguments.
In assembly level, nothing changes. Parameters are always located before ebp
(they were pushed before, but their address is higher than ebp
, so they come after it in some sense) starting from ebp + 8
(first argument). If somehow you know your int func(int a, int b, ...)
takes 43 parameters, you'll find them from ebp + 8
to ebp + 0x160
(assuming they're all int
s) (0x160 = 352dec = 8 + 43 * 4).
Of course the wrong number of parameters might make your program crash or behave strangely (like printf("%s")
)
The answer is it doesn't. The ANSI C89 standard that most compilers are based on does not define any method to detect what kinds of arguments are specified. printf() works because it has a format string that exactly specifies what arguments and their types are specified. You must somehow know what is being passed and use the va_* macros from stdarg.h accordingly. Section 4.8 of the draft ANSI C89 standard simply says the behavior is undefined if you request an incorrect type or incorrect number of arguments from what was actually passed.
Read this for the gory details from a draft of ANSI C89: http://flash-gordon.me.uk/ansi.c.txt
精彩评论