设为首页 加入收藏

TOP

C语言内存分配函数malloc、calloc和realloc
2014-04-07 00:36:37 】 浏览:216
Tags:语言 内存 分配 函数 malloc calloc realloc

  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 <STDIO.H>

  #include <STDLIB.H>

  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)。

 

  //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)。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇关于C语言中二维数组传参 下一篇C语言万年历代码

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目