V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
p64381
V2EX  ›  问与答

请教为什么 C 语言里对函数的里面的局部变量越界写后会改变上层调用函数里面的变量呢

  •  
  •   p64381 · Jan 27, 2018 · 2433 views
    This topic created in 3011 days ago, the information mentioned may be changed or developed.

    代码大致这样的

    #include <stdio.h>
    
    void fun2()
    {
    	struct tt
    	{
    		int len;
    		char buf[];
    	};
    	struct tt t1;
    	strcpy(t1.buf, "123456...."); // 这里造成越界写
    }
    
    void fun1()
    {
    	int i = 1;
    	fun2();
    	printf("i = %d\n", i); // 在开优化开 lto 的时候 i 的值会被 fun2 改变
    }
    
    

    我个人觉得这种情况应该是, 越界写改变栈的另外一个方向的内存啊, 不应该去改变上一层函数的变量啊. 还有为什么 valgrind 对这种情况一点都不吱声呢, 有什么工具能检查这种情况么?

    谢谢

    6 replies    2018-01-27 22:17:59 +08:00
    lovefantasy
        1
    lovefantasy  
       Jan 27, 2018 via Android   ❤️ 1
    geelaw
        2
    geelaw  
       Jan 27, 2018
    x86 的调用栈栈顶的地址数值小于栈底。
    p64381
        3
    p64381  
    OP
       Jan 27, 2018
    @lovefantasy 多谢。 这个很清楚的解释了为什么栈往下长。
    pkookp8
        4
    pkookp8  
       Jan 27, 2018 via Android
    一直搞不懂满升满降空升空降
    p64381
        5
    p64381  
    OP
       Jan 27, 2018
    @pkookp8 不知你在说什么
    gnaggnoyil
        6
    gnaggnoyil  
       Jan 27, 2018
    valgrind 不是用运行时 overhead 来检测 dynamic storage 的内存安全性的工具么?碰到像 LZ 这种 automatic storage 的情况一般都是无能为力吧?这种情况应该用 Clang 或者 GCC 的 UBsan 跑一遍.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5367 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 01:22 · PVG 09:22 · LAX 18:22 · JFK 21:22
    ♥ Do have faith in what you're doing.