首页 技术 正文
技术 2022年11月12日
0 收藏 907 点赞 4,628 浏览 1678 个字

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!\n");

  exit(0);

  }

  //print the allocated address

  printf("The address get by malloc is : %p\n",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!\n");

  exit(0);

  }

//print the allocated address

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

  //print the 4 integers at the beginning

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

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

  {

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

  }

  return 0;

  }

  执行结果例如以下:

  

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

  3、三者的联系

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

………………………………………………………………………………………………………………….

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,084
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,559
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,408
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,181
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,818
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,901