Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clarification on function pointers in C [duplicate]

Tags:

c

The following code comes from example abo3.c from Insecure Programming — see also Why cast extern puts to a function pointer (void(*)(char*))&puts?:

int main(int argv,char **argc) {
    extern system,puts; 
    void (*fn)(char*)=(void(*)(char*))&system; // <==
    char buf[256];
    fn=(void(*)(char*))&puts;
    strcpy(buf,argc[1]);
    fn(argc[2]);
    exit(1);
}

Specifically this line:

void (*fn)(char*)=(void(*)(char*))&system;

I think that void (*fn)(char*) sounds like a lambda, but I know that it's not. Then, maybe this is only a play with parentheses, where void *fn(char*) is a declaration of a function and this function is referencing system? But why does the (char*) parameter have no name? Is this permitted?

like image 655
gui_cc2015 Avatar asked Sep 16 '15 16:09

gui_cc2015


People also ask

What are function pointers in C?

Function pointers in C are variables that can store the memory address of functions and can be used in a program to create a function call to functions pointed by them.

What is the point of function pointers?

1) Unlike normal pointers, a function pointer points to code, not data. Typically a function pointer stores the start of executable code. 2) Unlike normal pointers, we do not allocate de-allocate memory using function pointers. 3) A function's name can also be used to get functions' address.


1 Answers

It declares the variable fn as a function pointer (to a function that has one argument of type char * and does not return anything (void).

This variable is initialised with the address of system - see http://linux.die.net/man/3/system. As noted from this page this will require the cast as given

like image 162
Ed Heal Avatar answered Sep 20 '22 21:09

Ed Heal