C语言之realloc函数

来源:互联网 发布:scopus数据库收录 编辑:程序博客网 时间:2024/06/12 00:41

【FROM MSDN && 百科】

【FROM:http://baike.baidu.com/view/736230.htm】

原型:  

void * realloc ( void * ptr, size_t size );

#include<stdlib.h>或#include <malloc.h>


指针名=数据类型*)realloc(要改变内存大小的指针名,新的大小)。//新的大小一定要大于原来的大小,不然的话会导致数据丢失!

Pointer to a memory block previously allocated with malloc, calloc or realloc, or a null pointer (to allocate a new block).

先判断当前的指针是否有足够的连续空间,如果有,扩大mem_address指向的地址,并且将mem_address返回,如果空间不够,先按照newsize指定的大小分配空间,将原有数据从头到尾拷贝到新分配的内存区域,而后释放原来mem_address所指内存区域,同时返回新分配的内存区域的首地址。即重新分配存储器块的地址。

百科中总结的关于realloc的用法

1. realloc失败的时候,返回NULL
2. realloc失败的时候,原来的内存不改变,不会释放也不会移动
3. 假如原来的内存后面还有足够多剩余内存的话,realloc的内存=原来的内存+剩余内存,realloc还是返回原来内存的地址; 假如原来的内存后面没有足够多剩余内存的话,realloc将申请新的内存,然后把原来的内存数据拷贝到新内存里,原来的内存将被free掉,realloc返回新内存的地址
4. 如果size为0,效果等同于free()。这里需要注意的是只对指针本身进行释放,例如对二维指针**a,对a调用realloc时只会释放一维,使用时谨防内存泄露。
5. 传递给realloc的指针必须是先前通过malloc(), calloc(), 或realloc()分配的,或者是NULL
6.传递给realloc的指针可以为空,等同于malloc。

DEMO:

//#define FIRST_DEMO#define SECOND_DEMO#ifdef FIRST_DEMO#include <stdio.h>#include <conio.h>#include <stdlib.h>int main(void){int i;int *pn=(int *)malloc(5*sizeof(int));printf("%p\n",pn);printf("input:");for (i=0;i<5;i++){scanf("%d",&pn[i]);}pn=(int *)realloc(pn,10*sizeof(int));printf("%p\n",pn);for (i=0;i<5;i++){printf("%3d",pn[i]);}printf("\n");free(pn);getch();return 0;}#elif defined SECOND_DEMO#include <stdio.h>#include <conio.h>#include <stdlib.h>int main(void){int input,n;int count=0;int *numbers=NULL;   //realloc  allocation memory int *more_numbers;do {printf("Enter an integer value(0 to end):");scanf("%d",&input);count++;/*Pointer to a memory block previously allocated with malloc, calloc or realloc, or a null pointer (to allocate a new block).*/more_numbers=(int *)realloc(numbers,count*sizeof(int));if (more_numbers !=NULL){numbers=more_numbers;numbers[count-1]=input;}else{free(numbers);puts("Error (re)allocating memory");exit(1);}} while (input!=0);printf("Numbers entered: ");for (n=0;n<count;n++){printf("%d",numbers[n]);}free(numbers);getch();return 0;}#endif