从地址调用函数时C ++程序崩溃

时间:2022-12-04 03:11:46
void print()
{
  printf("Test");
}

This does not work

这不起作用

Unhandled exception at 0x00402826 in test.exe: 0xC0000005: Access violation reading location 0x00000000.

test.exe中0x00402826处的未处理异常:0xC0000005:访问冲突读取位置0x00000000。

int main()
{
  typedef void function(void);
  function* Execute = (function*)0x00402810;
  Execute();
}

But this works?

但这有效吗?

int main()
{
  void(*func)();
  func = &print;
  cout << func;
  getchar();

  typedef void function(void);
  function* Execute = (function*)0x00402810;
  Execute();
 }

I am compiling with /Dynamicbase:NO

我正在使用/ Dynamicbase进行编译:没有

so addresses are static on every run.

所以地址在每次运行时都是静态的。

1 个解决方案

#1


There is no guarantee that when you declare print() before main() it is actually compiled to a few addresses before main() (As one might expect). From here, since the main() function on your second example is not the same as the first one (larger), the address of the print() function might have changed between the two examples.

无法保证当您在main()之前声明print()时,它实际上会在main()之前编译为几个地址(正如人们所期望的那样)。从这里开始,由于第二个示例中的main()函数与第一个示例中的main()函数不同(较大),因此print()函数的地址可能在两个示例之间发生了变化。

If you really want to find out the address of your function i'd recommend using a debugger to find that out.

如果你真的想找出你的函数的地址,我建议使用调试器找出它。

Hope it helps.

希望能帮助到你。

#1


There is no guarantee that when you declare print() before main() it is actually compiled to a few addresses before main() (As one might expect). From here, since the main() function on your second example is not the same as the first one (larger), the address of the print() function might have changed between the two examples.

无法保证当您在main()之前声明print()时,它实际上会在main()之前编译为几个地址(正如人们所期望的那样)。从这里开始,由于第二个示例中的main()函数与第一个示例中的main()函数不同(较大),因此print()函数的地址可能在两个示例之间发生了变化。

If you really want to find out the address of your function i'd recommend using a debugger to find that out.

如果你真的想找出你的函数的地址,我建议使用调试器找出它。

Hope it helps.

希望能帮助到你。