eXPerience eXPerience - 1 year ago 128
C++ Question

Value of pointer different from what it is assigned to

I have two empty functions called TestFunc and TestFunc2, and I assigned their addresses to two variables.

void TestFunc()

__declspec(naked) void TestFunc2()

int main()
DWORD* test = (DWORD*)TestFunc;
DWORD* test2 = (DWORD*)TestFunc2;

printf("TestFunc is %p at test is %p\n", TestFunc, test);
printf("TestFunc2 is %p at test2 is %p\n", TestFunc2, test2);

After assignment, the value of the two variables actually differ from what they are assigned.

However, in a printf statement, the output shows that they are the same. Any ideas why is this happening?


Answer Source

This is caused by incremental linking in Visual Studio, from this page you can learn that one of the drawbacks of this is:

An incrementally linked program is functionally equivalent to a program that is non-incrementally linked. However, because it is prepared for subsequent incremental links, an incrementally linked executable, static library, or dynamic-link library file:

  • Is larger than a non-incrementally linked program because of padding of code and data. Padding enables the linker to increase the size of functions and data without recreating the file.
  • May contain jump thunks to handle relocation of functions to new addresses.

and those jump thunks is what your have observed.

if you disable this option (vs2015):

Linker -> All Options -> Enable Incremental Linking to NO

then your addresses will be equal.

If you look closer in disassembly what is at the address which you have assigned to DWORD*, you will find that there is a jump to your function:

000000014001117C  jmp         TestFunc (01400116D0h)  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download