Pergunta

What happens if I pass more arguments than required to a function? I expected something to be corrupted in the called function, but everything works fine in some small test codes.

eg:

void print()
{
    int x=10;
    printf("%d\n",x);
}
void main()
{
    print(0,0,0,0,0);
}
Foi útil?

Solução

It is undefined behavior.

(C99, 6.5.2.2p6) "If the expression that denotes the called function has a type that does not include a prototype, [...] If the number of arguments does not equal the number of parameters, the behavior is undefined."

And we know from 6.9.1p7 that print function does not provide a prototype.

C99, 6.9.1p7) "If the declarator includes a parameter type list, the list also specifies the types of all the parameters; such a declarator also serves as a function prototype for later calls to the same function in the same translation unit. If the declarator includes an identifier list,142) the types of the parameters shall be declared in a following declaration list."

As there is no constraint violation, no diagnostic message is required.

Outras dicas

On a function call, the compiler will decide to put the arguments in the CPU register if they fit, otherwise, the arguments will go to the STACK memory (http://www.technochakra.com/wp-content/uploads/assembly_stack.jpg).

When you add arguments that doesn't exist, it may lead to undefined behavior since the called function code may missalign the stack memory access. In other words, the calling code will write the stack with a different layout of the expected layout inside the function.

A compile error will encounter. I compile the code in visual c++ 6.0, the compile output:

error C2660: 'print' : function does not take 5 parameters
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top