zoukankan      html  css  js  c++  java
  • C语言内存分配函数malloc——————【Badboy】

    C语言中经常使用的内存分配函数有malloc、calloc和realloc等三个,当中。最经常使用的肯定是malloc,这里简单说一下这三者的差别和联系。

      1、声明

      这三个函数都在stdlib.h库文件里,声明例如以下:

      void* realloc(void* ptr, unsigned newsize);

      void* malloc(unsigned size);

      void* calloc(size_t numElements, size_t sizeOfElement);

      它们的功能大致类似,就是向操作系统请求内存分配,假设分配成功就返回分配到的内存空间的地址。假设没有分配成功就返回NULL.

      2、功能

      malloc(size):在内存的动态存储区中分配一块长度为"size"字节的连续区域,返回该区域的首地址。

      calloc(n,size):在内存的动态存储区中分配n块长度为"size"字节的连续区域。返回首地址。

      realloc(*ptr,size):将ptr内存大小增大或缩小到size.

      须要注意的是realloc将ptr内存增大或缩小到size,这时新的空间不一定是在原来ptr的空间基础上,添加或减小长度来得到,而有可能(特别是在用realloc来增大ptr的内存空间的时候)会是在一个新的内存区域分配一个大空间,然后将原来ptr空间的内容复制到新内存空间的起始部分。然后将原来的空间释放掉。因此。一般要将realloc的返回值用一个指针来接收,以下是一个说明realloc函数的样例。

      #include

      #include

      int main()

      {

      //allocate space for 4 integers

      int *ptr=(int *)malloc(4*sizeof(int));

      if (!ptr)

      {

      printf("Allocation Falure! ");

      exit(0);

      }

      //print the allocated address

      printf("The address get by malloc is : %p ",ptr);

      //store 10、9、8、7 in the allocated space

      int i;

      for (i=0;i<4;i++)

      {

      ptr[i]=10-i;

      }

      //enlarge the space for 100 integers

      int *new_ptr=(int*)realloc(ptr,100*sizeof(int));

      if (!new_ptr)

      {

      printf("Second Allocation For Large Space Falure! ");

      exit(0);

      }


    //print the allocated address

      printf("The address get by realloc is : %p ",new_ptr);

      //print the 4 integers at the beginning

      printf("4 integers at the beginning is: ");

      for (i=0;i<4;i++)

      {

      printf("%d ",new_ptr[i]);

      }

      return 0;

      }

      执行结果例如以下:

      C语言内存分配函数malloc、calloc和realloc

      从上面能够看出,在这个样例中新的空间并非以原来的空间为基址分配的,而是又一次分配了一个大的空间,然后将原来空间的内容复制到了新空间的開始部分。

      3、三者的联系

      calloc(n,size)就相当于malloc(n*size),而realloc(*ptr,size)中。假设ptr为NULL,那么realloc(*ptr,size)就相当于malloc(size)。


    ..................................................................................................................................


  • 相关阅读:
    SharePoint 2013 配置基于表单的身份认证
    SharePoint 2013 场解决方案包含第三方程序集
    SharePoint 2010 站点附加数据升级到SP2013
    SharePoint 2013 在母版页中插入WebPart
    SharePoint 2013 搭建负载均衡(NLB)
    SharePoint 部署解决方案Feature ID冲突
    SharePoint 2013 配置基于AD的Form认证
    SharePoint Server 2016 Update
    SharePoint 2013 为用户组自定义EventReceiver
    SharePoint 2013 JavaScript API 记录
  • 原文地址:https://www.cnblogs.com/liguangsunls/p/7265273.html
Copyright © 2011-2022 走看看