从 stdin 传递函数名并在 C 中执行

Pass function name from stdin and execute in C

作为我正在处理的家庭作业的额外学分,我们必须尝试通过向以下代码的可执行文件提供输入来调用 win()(我们无法更改代码)。我们必须提供一个数字 n 和一个 target 的值,然后执行。我知道 n 的值是多少。我不是很精通 C,但我在这里查看了许多其他关于使用函数指针的问题,我认为传入 &win 会起作用,但只会打印 Third challenge 过多次数然后段故障。有人可以指出正确的方向,或者更多资源,以便我更好地理解函数指针在该程序中的工作方式吗?

typedef void (*funcptr_t)();


int win()
{
    printf("Great Job\n");
    exit(0);
}

int main()
{
    int n = 0;
    unsigned long long target;

    printf("Third challenge\n");
    scanf("%d", &n);
    scanf("%llu", &target);
    if (n == 0xc0decafe) {
        funcptr_t funcptr = (funcptr_t)target;
        funcptr();
    }
}

如果您事先能够以某种方式计算出 win 函数在运行时的地址,那么您可以提供该地址作为 target 输入值。然后代码将能够从该值中创建一个函数指针,这将对应于实际的 win 函数,然后调用该函数。

帮助您获取与给定函数关联的地址的工具通常是链接器,或某种 object/executable 转储实用程序。

有关工具的概述,请参阅 How does the linker find the main function?