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

寻求生成Valgrind错误Address 0x1c is not stack'd...的极简示例程序

极简C程序触发Valgrind "Address 0x1c is not stack'd, malloc'd or (recently) free'd"错误

没问题,给你一个超精简的示例,核心就一行代码,绝对能精准触发这个Valgrind错误。咱直接上完整代码:

#include <stdio.h>

int main() {
    // 直接读写非法内存地址0x1c
    *(int*)0x1c = 42;
    return 0;
}

为啥这行代码能触发目标错误?

  • 这里我们把0x1c这个硬编码的地址强制转换成int*指针,然后尝试给它赋值。这个地址既不是当前进程栈上的局部变量地址,也不是通过malloc/calloc分配的堆内存,更不是刚刚被free释放的内存——完全是一块不属于当前进程合法地址空间的“野地址”。

编译&运行步骤

  1. 编译代码(加-g让Valgrind能输出清晰的调用栈):
    gcc -g -o bad_access bad_access.c
    
  2. 用Valgrind运行程序:
    valgrind ./bad_access
    

你会看到的Valgrind错误输出(类似)

12345 Invalid write of size 4
12345 at 0x109142: main (bad_access.c:5)
12345 Address 0x1c is not stack'd, malloc'd or (recently) free'd
12345 Possible cause: stack overflow in main thread?
12345 by allocating too large a variable on the stack or calling a function
12345 that allocates a large variable on the stack
12345 If you believe this happened as a result of a stack overflow in your
12345 program's main thread (unlikely but possible), you can try to increase
12345 the size of the main thread stack using the --main-stacksize= flag.
12345 The main thread stack size used in this run was 8388608.

补充说明

这个错误的本质是进程访问了操作系统未分配给它的内存页,Valgrind的内存检测机制捕捉到了这个非法操作,就会抛出这个提示。用硬编码的小地址(这类地址通常属于内核空间或者未映射的空白区域)是最直接的触发方式,完全不需要复杂的逻辑,完美符合你要的“极简”需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 06:31:31