zoukankan      html  css  js  c++  java
  • dont return local address

    #include <iostream>
    #include <string>
    #ifdef __linux
    #include <stdio.h>
    #endif
    // 编译器真是相当友好啊warning C4172: returning address of local
    // variable or temporary 一定不要返回局部变量啊
    
    
    char* GetMemory(void)
    {
        char p[] = "hello world";
        return p; // 这里是返回local的address
    }
    
    int get_int(void)
    {
        int i = 3;
        return i; // 这是返回local的值,与上面是两回事,上面是说返回之后,用到这个地址返回值
    }             // 要用GetMemory这个函数里面的已经析构了的数据  
    // 而下面就涉及到get_int这个函数里面的local变量,因为别人只用这个int值
    int main()
    {
        char *str = NULL;
        //	std::cout << *str; //不可以这样输出0么?
        str = GetMemory();
        printf(str);
        std::cout << std::endl;
    
        std::cout << get_int() << std::endl;
        return 0;
    }
    
    DontReturnLocalAddress : DontReturnLocalAddress.cpp
    	g++ -g DontReturnLocalAddress.cpp -o DontReturnLocalAddress
    clean:
    	rm DontReturnLocalAddress
    

    23

  • 相关阅读:
    2019ICPC上海站
    “浪潮杯”第九届山东省ACM大学生程序设计竞赛重现赛(2018)
    集合问题
    后缀数组
    141. 周期(KMP)
    求和(矩阵快速幂)
    大数(KMP)
    1270: [蓝桥杯2015决赛]完美正方形
    AC自动机
    8.26作业
  • 原文地址:https://www.cnblogs.com/sunyongjie1984/p/4258921.html
Copyright © 2011-2022 走看看