Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deciphering (*(void(*)())0)()

They said this expression is valid in C, and that it means calling a function:

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

Can someone clearly explain what this expression means?

I tried to compile this and was surprised that it didn't result in an error.

like image 662
NguyenDat Avatar asked Apr 09 '10 00:04

NguyenDat


2 Answers

Step by step:

   void(*)()        // a pointer-to-function type, taking unspecified parameters
                    // and returning nothing.
  (void(*)())0      // a null pointer of that pointer-to-function type
(*(void(*)())0)     // dereference that pointer
(*(void(*)())0)();  // and call it with no parameters

The code has undefined behaviour, it'll probably crash with some kind of illegal access / segfault.

like image 83
Steve Jessop Avatar answered Sep 24 '22 07:09

Steve Jessop


You are creating a pointer to a function and then calling it. I wouldn't call it a hidden feature but undefined behavior.

Basically you are doing this but with the address 0 instead:

void test() { }

void(*pfn)() = test;
(*pfn)();
like image 43
Brian R. Bondy Avatar answered Sep 24 '22 07:09

Brian R. Bondy