You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

不使用call/jump调用及study函数,实现指定顺序输出的C语言问题

解决方案:利用栈内存与函数指针实现指定输出逻辑

需求回顾

  • 禁止直接调用study(),也不能使用call/jump类指令
  • 程序需先输出this is the first,再输出this is the second.
  • 仅允许修改study2()中标记的代码段,必须利用bold数组完成

修改后的代码

#include <stdio.h>

void study()
{
    printf("this is the second.\n");
}

void study2()
{
    int bold[4];
    // can only modify this section BEGIN
    // 通过栈内存覆盖返回地址,将study的地址写入返回位置
    *(void**)(&bold[4]) = (void*)study;
    // can only modify this section END
    printf("this is the first\n");
}

int main(int argc, char *argv[])
{
    study2();
    return 0;
}

原理说明

在x86架构的栈帧布局中,study2函数的栈空间结构大致为:局部变量bold数组 → 基址指针EBP → 返回地址(指向main中调用study2后的下一条指令)。

我们通过&bold[4]获取到数组末尾之后的内存位置,这个位置恰好对应栈中存储返回地址的区域。将study函数的地址写入该位置后,当study2执行完printf("this is the first")并执行ret指令时,程序会跳转到study函数执行,从而输出this is the second.,最终study执行完毕后返回main,完成整个流程。

这种方式没有直接调用study(),也没有使用call/jump指令,完全通过修改栈上的返回地址实现了预期的执行顺序,符合所有限制条件。

内容的提问来源于stack exchange,提问作者SugarFree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 05:23:29