【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返回新內存的地址
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