?
This document uses PHP Chinese website manual Release
在頭文件<stdlib.h>中定義 | ||
---|---|---|
void * realloc(void * ptr,size_t new_size); |
重新分配給定的內(nèi)存區(qū)域。它必須預(yù)先分配malloc()
,calloc()
或realloc()
尚未釋放與free
或呼叫realloc
。否則,結(jié)果是不確定的。
重新分配由以下兩者之一完成:
a)ptr
如有可能,擴(kuò)大或縮小指定的現(xiàn)有地區(qū)。該地區(qū)的內(nèi)容保持不變,直至新舊尺寸中的較小者。如果區(qū)域展開(kāi),則數(shù)組新部分的內(nèi)容未定義。
b)分配一個(gè)大小為new_size
字節(jié)的新內(nèi)存塊,復(fù)制大小等于新舊大小較小者的內(nèi)存區(qū)域,并釋放舊塊。
如果沒(méi)有足夠的內(nèi)存,則舊的內(nèi)存塊不會(huì)被釋放,并返回空指針。
如果ptr
是NULL
,則行為與調(diào)用malloc
(new_size
)相同。
如果new_size
為零,則行為是實(shí)現(xiàn)定義的(可能會(huì)返回空指針(在這種情況下,可能會(huì)釋放或不釋放舊的內(nèi)存塊),或者可能會(huì)返回一些可能不用于訪問(wèn)存儲(chǔ)的非空指針)。
realloc是線程安全的:它的行為就像訪問(wèn)通過(guò)其參數(shù)可見(jiàn)的內(nèi)存位置,而不是任何靜態(tài)存儲(chǔ)。先前調(diào)用free或realloc來(lái)釋放內(nèi)存區(qū)域的同步 - 調(diào)用任何分配函數(shù),包括分配相同或部分同一區(qū)域內(nèi)存的realloc。在通過(guò)釋放函數(shù)訪問(wèn)內(nèi)存之后以及在通過(guò)重新分配訪問(wèn)內(nèi)存之前,會(huì)發(fā)生此同步。所有分配和解除分配功能在內(nèi)存的每個(gè)特定區(qū)域都有一個(gè)總的順序。 | (自C11以來(lái)) |
---|
PTR | - | 指向要重新分配的內(nèi)存區(qū)域的指針 |
---|---|---|
new_size | - | 數(shù)組的新大小 |
成功時(shí),將指針?lè)祷氐叫路峙涞膬?nèi)存的開(kāi)始位置。返回的指針必須用free()
或來(lái)解除分配realloc()
。原始指針ptr
無(wú)效,并且對(duì)它的任何訪問(wèn)都是未定義的行為(即使重新分配就地)。
失敗時(shí),返回一個(gè)空指針。原始指針ptr
仍然有效,可能需要使用free()
or 取消分配realloc()
。
從C11 DR 400開(kāi)始不支持零大小。
最初(在C89中),增加了對(duì)零大小的支持以適應(yīng)如下代碼。
OBJ *p = calloc(0, sizeof(OBJ)); // "zero-length" placeholder...while(1) { p = realloc(p, c * sizeof(OBJ)); // reallocations until size settles ... // code that may change c or break out of loop}
#include <stdio.h>#include <stdlib.h> int main(void){ int *pa = malloc(10 * sizeof *pa); // allocate an array of 10 int if(pa) { printf("%zu bytes allocated. Storing ints: ", 10*sizeof(int)); for(int n = 0; n < 10; ++n) printf("%d ", pa[n] = n); } int *pb = realloc(pa, 1000000 * sizeof *pb); // reallocate array to a larger size if(pb) { printf("\n%zu bytes allocated, first 10 ints are: ", 1000000*sizeof(int)); for(int n = 0; n < 10; ++n) printf("%d ", pb[n]); // show the array free(pb); } else { // if realloc failed, the original pointer needs to be freed free(pa); }}
輸出:
40 bytes allocated. Storing ints: 0 1 2 3 4 5 6 7 8 94000000 bytes allocated, first 10 ints are: 0 1 2 3 4 5 6 7 8 9
C11標(biāo)準(zhǔn)(ISO / IEC 9899:2011):
7.22.3.5 realloc函數(shù)(p:349)
C99標(biāo)準(zhǔn)(ISO / IEC 9899:1999):
7.20.3.4 realloc函數(shù)(p:314)
C89 / C90標(biāo)準(zhǔn)(ISO / IEC 9899:1990):
4.10.3.4 realloc函數(shù)