![](/img/trans.png)
[英]Is there a way to either query what would realloc do, or prevent it from copying all memory on Windows and Linux?
[英]What would realloc do if there is no sequential space of memory?
realloc
用於動態重新分配內存。
假設我使用malloc
函數分配了7個字節,現在我想將它擴展到30個字節。
如果內存中沒有30個字節的連續(連續單行)空間,后台會發生什么?
是否有任何錯誤或內存將被分配?
realloc
在幕后工作大致如下:
NULL
報告失敗。 因此,您可以通過測試NULL
來測試失敗,但請注意,您不要過早覆蓋舊指針:
int* p = malloc(x);
/* ... */
p = realloc(p, y); /* WRONG: Old pointer lost if realloc fails: memory leak! */
/* Correct way: */
{
int* temp = realloc(p, y);
if (NULL == temp)
{
/* Handle error; p is still valid */
}
else
{
/* p now possibly points to deallocated memory. Overwrite it with the pointer
to the new block, to start using that */
p = temp;
}
}
realloc
只有在它能夠返回連續的(你的話中的“順序”)內存塊時才會成功。 如果不存在這樣的塊,則它將返回NULL
。
從手冊頁 :
realloc()返回一個指向新分配的內存的指針,該內存適用於任何類型的變量,可能與ptr不同,如果請求失敗,則返回NULL。
換句話說,要檢測失敗,只需檢查結果是否為NULL。
編輯:如評論中所述,如果調用失敗,則不會釋放原始內存。
一般來說,這取決於實施。 在x86(-64)Linux上,我相信標准的doug lea malloc算法總是會分配最小的標准x86頁面(4096字節),因此對於上面描述的場景,它只會重置邊界以容納額外的字節。 比如說,重新分配7bytes的緩沖區到PAGE_SIZE + 1,我相信它會嘗試分配下一個連續頁面(如果可用)。
如果你在Linux上開發,請閱讀以下內容:
默認情況下,Linux遵循樂觀的內存分配策略。 這意味着當malloc()返回非NULL時,無法保證內存確實可用。 這是一個非常糟糕的錯誤。 如果事實證明系統內存不足,臭名昭着的OOM殺手就會殺死一個或多個進程。 如果在不太可能突然丟失一些隨機選擇的進程的情況下使用Linux,而且內核版本足夠新,可以使用如下命令關閉這種過度使用的行為:
# echo 2 > /proc/sys/vm/overcommit_memory
另請參閱內核文檔目錄,文件vm / overcommit-accounting和sysctl / vm.txt。
FreeBSD和Mac OS X都有reallocf()函數,當無法分配請求的內存時,它將釋放傳遞的指針(參見man realloc)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.