Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perhaps a function pointer or casting problem. Not sure

Tags:

c

string

What's happening in this code? I don't get this code. Looks like it's performing some type of casting or using function pointers but I'm not sure. Will appreciate if someone can help me. Thanks.

const char string[]="Hello!";

int main()   
{

    (*(void (*)()) string)(); //Obviously, my problem is this line :)

    return 0;
}
like image 470
Naruto Avatar asked Dec 13 '25 07:12

Naruto


1 Answers

First, let's use cdecl to explain the inner gibberish:

$ cdecl
cdecl> explain (void (*)())
cast unknown_name into pointer to function returning void

So (void (*)()) string casts string into a function pointer. Then the function pointer is dereferenced to call the underlying function. The line is equivalent to

void (*fp)() = (*(void (*)()) string)();
(*fp)();

This (on most machines) tries to execute "Hello!" as machine code. It may crash outright on machines with virtual memory because data is often marked as non-executable. If it doesn't crash, it's not likely to do anything coherent. In any case, this is not useful code.

The only thing to learn here is that the cdecl tool can be useful to understand or write complicated C types and declarations.

like image 124
Gilles 'SO- stop being evil' Avatar answered Dec 15 '25 04:12

Gilles 'SO- stop being evil'