C語言之realloc函數

【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 malloccalloc 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


發佈了90 篇原創文章 · 獲贊 68 · 訪問量 66萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章