consider following code:
#include <iostream> typedef int (*test_func_t) (int, int, int); int print_integer (int a) { std::cout << "num: " << << "\n"; return a; } int main (int argc, char * argv[]) { test_func_t func = (test_func_t) &print_integer; std::cout << "calling 3 parameters func(5,7,9)\n"; func(5,7,9); return 0; } as can see, type (test_func_t) defined function 3 int arguments. function pointer (func) assigned pointer "print_integer", receives 1 argument, , function pointer called 3 arguments (5, 7, 9).
this code works , produces "num: 5" output.
gdb disas output (intel syntax)
disas main ... 0x080486cb <+9>: mov dword ptr [esp+0x1c],0x804867d ... 0x080486e0 <+37>: mov dword ptr [esp+0x8],0x9 0x080486e8 <+45>: mov dword ptr [esp+0x4],0x7 0x080486f0 <+53>: mov dword ptr [esp],0x5 0x080486f7 <+60>: mov eax,dword ptr [esp+0x1c] 0x080486fb <+64>: call eax disas print_integer ... 0x08048683 <+6>: mov dword ptr [esp+0x4],0x8048830 0x0804868b <+14>: mov dword ptr [esp],0x8049ae0 0x08048692 <+21>: call 0x8048530 <std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)@plt> 0x08048697 <+26>: mov edx,dword ptr [ebp+0x8] 0x0804869a <+29>: mov dword ptr [esp+0x4],edx 0x0804869e <+33>: mov dword ptr [esp],eax 0x080486a1 <+36>: call 0x80484d0 <std::ostream::operator<<(int)@plt> as can see, rest of arguments ([ebp+0x12] , [ebp+0x16]) not used.
my questions:
- this seems work on linux x86 __cdecl calling convention. safe on other architectures , calling conventions well?
- does c/c++ standard allows/defines result of assigning function pointer function expects fewer arguments?
example of such use: node.js's node_module registers function type has 3 arguments [exports, module, priv]. called 3 formal examples show registering of function 1 or 2 arguments.
quoting c++11 standard expr.reinterpret.cast 6:
a function pointer can explicitly converted function pointer of different type. effect of calling function through pointer function type (8.3.5) is not same type used in definition of function undefined.
so, i'd not safe in general. undefined behaviour. said, don't know how other implementation of c++ behave in situation.
Comments
Post a Comment