What will be output of simple C function and why?

109 views Asked by At

I need to understand and reproduce (in another language) logic of following function (C code) and I don't really understand, what it is doing

double __thiscall sub_1(int this) {

    return * (double *) (this + 12);

}

It's compiled OK, but crashed while running .exe file

I'm not strong with C at all, and cannot find out, what actual manipulation this set of operands is doing * (double *) It's not a dereferencing, because there is no pointers declared.

Anyway, can anyone tell me - what will be output of function

for sub_1(2) and why ?

1

There are 1 answers

2
Lundin On

For this code to work, int this must be a variable holding the integer value of an address. From that address, there must be a valid double allocated, with a 12 byte offset. The code returns the contents of that double.

So if the function is called as sub_1(0x00000010), then there must be a double variable allocated at address 0x0000001C. If not, the program invokes undefined behavior and will most likely crash & burn.

Please note that it doesn't make any sense to use int to pass an address. A better choice would have been double*, or at least uint32_t which isn't a signed integer type. This code would have failed if the address was too large to fit inside an int.