zoukankan      html  css  js  c++  java
  • GetMemory()函数

    NO1

    void GetMemory(char *p)

    {

           p=(char *)malloc(100);

    }

    void Test()

    {

      char * str=NULL;

      GetMemory(str);

      strcpy(str,"Hello world");

      printf(str);

    }

     

    实质:GetMemory(str)在调用时会生成一个_str与str指向同一个数,这是因为C语言中函数传递形参不改变实参的内容,但是指针指向的内容是相同的,因此可以用指针控制数据。题中的GetMemory(str),实质是对_str的操作,并没有对str操作,函数结束后_str撤销,因此不会产生新的内存空间,str仍然是一个空指针。

     

    NO2

    char *GetMemory()

    {

           char p[]="Hello World";

           return p;

    }

    void Test()

    {

           char * str=NULL;

           str=GetMemory();

           printf(str);

    }

    实质:当一个函数调用结束后会释放内存空间,释放它所有变量所占用的空间,所以数组空间被释放掉了,也就是说str所指向的内容不确定是什么东西。但是返回的指针指向的地址是一定的。

     

    NO3

    char *GetMemory()

    {

           Return “hello world”;

    }

    void Test()

    {

           char * str=NULL;

           str=GetMemory();

           printf(str);

    }

    实质:本例打印hello world,因为返回常量区,而且并没有修改过。在上一个例子中不一定能打印hello world,因为指向的是栈区。

     

    NO4

    void GetMemory(char **p,int num)

    {

           *p=(char *)malloc(num);

    }

    void Test()

    {

           char * str=NULL;

           GetMemory(&str,100);

           strcpy(str,"Hello");

           printf(str);

    }

    可以正确的打印Hello但是内存泄露了,在GetMemory()中使用了malloc申请内存,但是在最后却没有对申请的内存做任何处理,因此可能导致内存的泄露,非常危险。

     

    NO5

    void Test()

    {

           char *str=(char *)malloc(100);

           strcpy(str,"Hello");

           free(str);

           if (str!=NULL)

           {

                  strcpy(str,"World");

                  printf(str);

           }

    }

    申请空间,拷贝字符串,释放空间,前三步操作都没有问题,到了if语句里的判断条件开始出错了。因为一个指针被释放了之后其内容并不是NULL,而是一个不确定的值,所以if语句永远不能被执行,这也是著名的“野”指针问题。

     

    NO6

    void GetMemory(void)

    {

           char *str=(char *)malloc(100);

           strcpy(str,"hello");

           free(str);

           if (str !=NULL)

           {

                  strcpy(str,"world");

                  printf(str);

           }

    }

    Str 为野指针,打印的结果不能确定。

  • 相关阅读:
    纪伯伦:我曾七次鄙视我的灵魂
    字典和集合
    元组
    列表
    字符串
    数值类型
    内置函数了解一下
    了解Python
    centos7安装mysql数据库
    xenserver 上传centos6.8镜像
  • 原文地址:https://www.cnblogs.com/try-again/p/4307839.html
Copyright © 2011-2022 走看看