zoukankan      html  css  js  c++  java
  • C内存管理

    内存管理

    将函数中命令、语句编译成相应序列的机器指令代码,放在代码段中;

    将已初始化的数据,如已赋值的全局变量、静态局部变量等放在数据段内;

    将未初始化的数据放在BSS段内;

    将临时数据,如函数调用时传递的参数、局部变量、返回调用时的地址等放在栈段内;

    而对一些动态变化的数据,如在程序执行中建立的一些数据结构,如链表、动态数组等放在堆结构中。

    Malloc()和free()来分配和释放内存

    PC机存储器分为主存储器、外存储器和高速缓存(Cache)几个部分

    堆是一种动态存储的结构,实际上就是数据段中的自由存储区,他是C语言中使用的一中名称,常常用于动态数据结构存储分配。

    堆管理函数:

    Malloc()  free()  realloc()          calloc()  

    1. malloc()

    void *malloc( unsigned size );

    向系统申请分配指定size个字节的内村空间,返回类型是void类型。

    int *p;

    p = ( int * ) malloc ( sizeof(int) );

    例程:

    #include< stdio.h >

    #include< stdlib.h >

    main()

    {

           char *str;

           if( ( str = (char *)malloc(50)) == NULL )

           {

                  printf( "\n No enough memory to allocata for the string." );

                  exit(1);

           }

          

           printf("\n Input the string:");

           gets(str);

           puts(str);

           free(str);

    }

    1. free()函数

    free()函数用来释放内存

    void *free( void *block );

    int *p = (int *)malloc(4);

    *p = 100;

    Free(p);

    例程:

    #include<stdlib.h>

    #include<stdio.h>

    main()

    {

           char *str;

           if( (str = (char *)malloc(10)) == NULL )

           {

                  printf("\n Allocation is failed.");

                  exit(1);

           }

           else

           {

                  printf("\n Input the string:");

                  gets(str);

           }

           puts(str);

           free(str);

    }

    1. realloc()函数

    用来重调空间的大小

    #include<stdlib.h>

    #include<stdio.h>

    main()

    {

           char *str;

           str = (char *)malloc( 10 );

           if( !str )

           {

                  printf("\n Allocation is failed");

                  exit(1);

           }

           printf("\n Input the string:");

           gets( str );

           str = ( char * )realloc( str, 20 );

           if( !str )

           {

                  printf("\n Allocation is failed ");

                  exit(1);

           }

           puts(str);

           free(str);

    }

    1. calloc()函数

    void *calloc( size_t nelem, size_t elsize );

    该函数将分配一个容量为nelem * size 大小的空间,并用0初始化内存区域,即每个地址装入0,该函数将返回指向分配空间的指针。如果没有空间可用,则返回NULL指针。

  • 相关阅读:
    SpringFramework中的BeanWrapper丶PropertyEditor
    Spring加载资源文件的方式
    kettle批量导入json数据
    Beanfactory与ApplicationContext
    fastjson的方法应用与java JSONObject
    算法 汽水瓶
    算法 简单密码
    算法 识别有效ip地址和掩码并做统计
    各类IP地址
    算法 密码验证合格程序
  • 原文地址:https://www.cnblogs.com/tao560532/p/2486894.html
Copyright © 2011-2022 走看看