zoukankan      html  css  js  c++  java
  • 内存四区-栈区

      局部变量存放在栈区,函数return以后申请的这块栈区就被回收(C++编译器把这段内存析构了),所以在函数内声明的局部变量,函数外不能使用该局部变量的内存地址。下面用代码说明:

    #define _CRT_SECURE_NO_WARNINGS
    #include <stdlib.h>
    #include <string.h>
    #include <stdio.h>

    char *getMem()
    {
      char buf[32]; //因为buf是临时变量,是放在栈区存放
      strcpy(buf, "I love u");
      return buf;
    }

    int main()
    {
      char *tmp = NULL;
      tmp = getMem();  //getMem函数return以后,buf数组占用的32字节的栈区已经被析构了,tmp接收到的只是这段内存的内存地址,可能是乱码,可能是任何东西

      printf("%s ", tmp);
      system("pause");
      return 0;
    }

    用DevC++运行报错:function returns address of local variable (函数返回局部变量的地址)

    用VS2017 Debug项目:

    不知道指向了哪块内存

    用VS2017 Release项目:

    可以正常显示

    看到用VS2017 Release虽然可以正常显示,但是这样写代码明显是不可以的。

     如果getMem函数不是返回地址,而是返回char类型变量的话可以,如下:

    char getMem()
    {
      char buf[32]; //因为buf是临时变量,是放在栈区存放
      strcpy(buf, "I love u");
      return buf[0];
    }

    int main()
    {
      char tmp = getMem(); //getMem函数return以后,会用buf[0]的值 I 放到tmp的内存地址(栈区)
      printf("%c ", tmp);
      system("pause");
      return 0;
    }

  • 相关阅读:
    IIS 备份
    Windows Service 的注册和卸载
    算法测试(课上测试)
    《Unix/Linux系统编程》第十四章学习笔记20191304商苏赫
    mystat
    实验四 Web服务器1socket编程
    《Unix/Linux系统编程》第十二章学习笔记20191304商苏赫
    整数范围与类型转换
    《Unix/Linux系统编程》第十三章学习笔记20191304商苏赫
    实验四 Web服务器2
  • 原文地址:https://www.cnblogs.com/fengxing999/p/10223741.html
Copyright © 2011-2022 走看看