zoukankan      html  css  js  c++  java
  • 关于内存分配的几个例子

    1. 

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    void GetMemory(char *p);
    
    void Test();
    
    int main()
    {
    	Test();
    	return 0;
    }
    
    void GetMemory( char *p )
    {
    	p = (char *) malloc( 100 );
    }
    
    void Test( void )
    {
    	char *str = NULL;
    	GetMemory( str );
    	strcpy( str, "hello world" );
    	printf(str);
    }
    分析:

    在VS2010上编译可以通过,但是不能运行。

    个人理解:

    运行GetMemory()时,p是str的一个副本。虽然分配的空间没有被销毁,但是GetMemory只是让p指向分配好的空间,而没有让Test中的str也指向malloc分配的内存

    所以不能运行。

    Test中,str初始化为NULL(不再是野指针了),因此,strcpy可以通过编译。


    2. 

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    void GetMemory(char *p);
    
    void Test();
    
    int main()
    {
    	Test();
    	return 0;
    }
    
    char *GetMemory( void )
    {
    	char p[] = "hello world";
    	return p;
    }
    
    void Test( void )
    {
    	char *str = NULL;
    	str = GetMemory();
    	printf( str );
    }

    结果:编译通过,运行时输出随机值

    原因:p为局部变量,函数执行完时被销毁。

    注:函数执行完时,


    3. 

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    char *tmp;
    void GetMemory(char *p);
    void Test();
    
    int main()
    {
    	Test();
    	return 0;
    }
    
    char *GetMemory( void )
    {
    	char *p = "hello world";
    //	tmp = p;
    	return p;
    }
    
    void Test( void )
    {
    	char *str = NULL;
    	str = GetMemory();
    	printf( str );
    }

    编译运行均没有问题,可以输出helloworld

    “Hello world”在静态去

    GetMemory将它的地址返回了。

    4. 

  • 相关阅读:
    CI框架源码学习笔记1——index.php
    angular.js的post数据方式
    腾讯2018年9月秋招前端笔试题--编程题
    有赞2018年9月秋招一面
    2018阿里秋招笔试编程题
    css3 flex布局
    tomcat启动后,无法访问,报404
    2018网易前端实习面试总结
    2018网易前端实习笔试编程题总结
    set用法
  • 原文地址:https://www.cnblogs.com/Windeal/p/4284685.html
Copyright © 2011-2022 走看看