• Advertisement

Archived

This topic is now archived and is closed to further replies.

Insane inline assembly

This topic is 5733 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Can anyone figure out how the following program prints "1234"?
  
#include <iostream>

int main() {
    long i[2];
    i[0] = 158136;
    i[1] = -1010826496;
    std::cout << (*(int(*)())i)() << std::endl;

    return 0;
}
  
Strange, eh? Firebird Entertainment

Share this post


Link to post
Share on other sites
Advertisement
Yeah its so insane that it doesn''t compile! At least on VC++. Pls tell what I''m doing wrong:
c:\my projects\c++\test\main.cpp(7) : error C2440: ''type cast'' : cannot convert from ''long [2]'' to ''int (__cdecl *)(void)''

Share this post


Link to post
Share on other sites
I''ll try to explain it.

Let''s examine (*(int(*)())i)().

int(*)() is a function pointer, returning int and taking no parameters. Let''s say we have typedef int(*FuncPtr)().

Then the code becomes (*(FuncPtr)i)()

It''s a little clearer now. It''s casting i to a function pointer and calling it. So the array i contains machine code. Let''s convert the decimal numbers into hex, and disassemble the result:

B8 69 02 00 00 // mov eax, 617
03 C0 // add eax, eax
C3 // ret


It''s loading 617 into eax, adding it to itself, and returning. And of course, 617 + 617 = 1234.

Share this post


Link to post
Share on other sites

  • Advertisement