简体   繁体   中英

Odd C syntax in pointer declaration and function call

Before anyone suggests the cdecl tool, I have already tried it. Strangely enough, most of the statements queried are returned with a syntax error warning.

Below is a C program I found online that does nothing but run a piece of shellcode.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv) {

char shellcode[] = "\xb0\x01\x31\xdb\xcd\x80";     

int (*func)();

func = (int (*)()) shellcode;
(int)(*func)();

return 0;

}

The program works as intended, but the C syntax is among the strangest I ever seen. I will try to interpret them as best I can.

int (*func)();

This statement declares func as a pointer (indicated by '*') to a function (indicated by '()') that returns an int.

func = (int (*)()) shellcode;

This statement typecasts the shellcode array as a pointer (indicated by '(*)') to a function (indicated by '()') that returns an int and assigns the pointer to func.

(int)(*func)();

This final statement executes the function (indicated by '()') pointed to by the pointer func (indicated by '(*func)') and typecasts the result as an integer.

I think that is what is going on here. If anyone more experienced with C sees any mistakes with my interpretations or can provide an alternative or more educational interpretation, I very much welcome your input.

I have never written variable initializations or function calls like this, so I am somewhat still quite confused about the syntax displayed. If you have a more readable way to write the code above, please also provide input.

Thank you.

That's all correct, although I don't get why it casts the return value to an int; my suspicion is that even who wrote that wasn't all that confident with C function pointer syntax.

In the real world you would probably see the that code written using a typedef:

typedef (*funcT)();
funcT func = (funcT) shellcode;
(*func)();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM