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. 

  • 相关阅读:
    UVA 120 Stacks of Flapjacks
    HDU 4869 Turn the pokers
    HDU 4882 ZCC Loves Codefires
    HDU 4864 Task
    HDU 4861 Couple doubi
    UVA 1600 Patrol Robot
    UVA 712 S-Trees
    2014/4/6长沙多校第六次(浙大校赛)
    UVA10905 思维考察
    HDU1498 枚举+二分图类棋盘问题(最大匹配)
  • 原文地址:https://www.cnblogs.com/Windeal/p/4284685.html
Copyright © 2011-2022 走看看