Reputation: 1326
i have defined the fun pointer type as
typedef void (*fn)(void)
declared a pointer variable : fn var = NULL; have written a small function void fun(void){} Now, i want to copy the address space of function fun into var variable using memcpy. I am trying this : memcpy(var, &fun, sizeof(fn))
But, when i printing the value of var it is showing up the garbage or negative value, and invoking the function from var is resulting into segmentation fault. pls help, where am i wrong here.
Upvotes: 0
Views: 1540
Reputation: 21507
Your code is probably memcpy(&var,&fun,sizeof(fn))
, or it would fail instantly with var
initialized to NULL
.
The memcpy
above is copying first bytes of fun
's code to var
, which is not what you want (not that it's a defined behavior by any standard, it's just how it probably happens to misbehave on your OS/compiler).
Use just var = fun;
instead.
If you're determined to play with memcpy
(for fun or learning), you'll have to get a variable containing a pointer to function first, not just a value of that pointer:
fn var1 = fun;
fn var2 = NULL;
memcpy(&var2,&var1,sizeof(fn));
var2();
Upvotes: 1