What does ((void (*)())buf)(); mean?

CFunctionPointersFunction Pointers

C Problem Overview


I am solving a binary exploitation challenge on picoCTF and came across this piece of code:

((void (*)())buf)();

where buf is a character array.

I solved the challenge but can't seem to understand what exactly it's doing. I looked at this thread but I couldn't make it out.

What does ((void (*)())buf)(); mean?

C Solutions


Solution 1 - C

void (*)() is a type, the type being "pointer to function that takes indeterminate arguments and returns no value".

(void (*)()) is a type-cast to the above type.

(void (*)())buf casts buf to the above type.

((void (*)())buf)() calls the function (passing no arguments).

In short: It tells the compiler to treat buf as a pointer to a function, and to call that function.

Solution 2 - C

pointer buf is converted to the pointer to void function taking unspecified number of parameters and then dereferenced (ie function called).

Solution 3 - C

It's a typecast, followed by a function call. Firstly, buf is cast to the pointer to a function that returns void. The last pair of parenthesis means that the function is then called.

Solution 4 - C

It casts the character array to a pointer to a function taking no arguments and returning void, and then calls it. Dereferencing the pointer is not required due to how function pointers work.

An explanation:

That "character array" is actually an array of machine code. When you cast the array to a void (*)() and call it, it runs the machine code inside of the array. If you provided the array's contents I could disassemble it for you and tell you what it's doing.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsh.3.llView Question on Stackoverflow
Solution 1 - CSome programmer dudeView Answer on Stackoverflow
Solution 2 - C0___________View Answer on Stackoverflow
Solution 3 - ClukegView Answer on Stackoverflow
Solution 4 - CS.S. AnneView Answer on Stackoverflow