Wednesday, July 30, 2008

How to call a function at memory address 0

As per Andrew Koenig, this is about understanding declarations in the paper, c traps and pitfalls.


(* (void (*)()) 0)();


int i: i is an int

int *i: *i is an int, i is a pointer to int

int fi(): fi() is int, fi is a function that returns int

int *gi(): *gi() or *(gi()) is int, gi() returns a pointer to int, gi is a function that returns a pointer to int. As () binds tighter than *, *gi() is same as *(gi())

int (*fi)(): (*fi)() is int, *fi is a function that returns an int, fi is a pointer to a function that returns an int. Also, (*fi)() would be the call statement to the function.

Based on this, the above declaration is divided into two parts.
(* 0)()  - this is similar to (*fi)() explained above. This calls the function at 0 using the pointer to a function at 0.

The only thing missing is that we need to cast 0 to a type of pointer to a function returning void which is done by void (*)().

void (*)() - For (*fi)(), fi is pointer to a function where fi is a dummy variable. So void (*)() is a pointer to a function returning void. For type-casting, we enclose it in brackets as (void (*)()).

Thus,


(* (void (*)()) 0)();



[Hat tip to Haroon Saeed, C Traps and Pitfalls]

No comments:

Post a Comment