malloc申请得到的内存后,再free释放它的时候,操作系统会立即收回那块内存吗?
stackoverflow上的回答:
In many malloc/free?implementations,?free?does?normally?not?return?the?memory?to?the?operating?system?(or?at?least?only?in?rare?cases).?The?reason?is,?that?you?will?get?gaps?in?your?heap?and?thus?it?can?happen,?that?you?just?finish?off?your?2?or?4?GB?of?virtual?memory?with?gaps.?This?should?be?avoided?of?course,?since?as?soon?as?the?virtual?memory?is?finished,?you?will?be?in?really?big?trouble.?The?other?reason?of?course?is,?that?the?OS?can?only?handle?memory?chunks?that?are?of?a?specific?size?and?alignment.?To?be?specific:?Normally?the?OS?can?only?handle?blocks?that?the?virtual?memory?manager?can?handle?(most?often?multiples?of?512?Bytes?eg.?4KB).
So?returning?40?Bytes?to?the?OS?will?just?not?work.?So?what?does?free?do?
Free?will?put?the?memory?block?in?its?own?free?block?list.?Normally?it?also?tries?to?meld?together?adjacent?blocks?in?the?address?space.?The?free?block?list?is?just?a?circular?list?of?memory?chunks?which?have?of?course?some?administrative?data?in?the?beginning.?This?is?also?the?reason,?why?managing?very?small?memory?elements?with?the?standard?malloc/free?is?not?efficient.?Every?memory?chunk?needs?additional?data?and?with?smaller?sizes?more?fragmentation?happens.
The?free-list?is?also?the?first?place?that?malloc?looks?at?when?a?new?chunk?of?memory?is?needed.?It?is?scanned?before?it?calls?for?new?memory?from?the?OS.?When?a?chunk?is?found?that?is?bigger?then?the?needed?memory,?it?is?just?divided?into?two?parts.?One?is?returned?to?caller,?the?other?is?put?back?into?the?free?list.
There?are?many?different?optimizations?to?this?standard?behaviour?(for?example?for?small?chunks?of?memory).?But?since?malloc?and?free?must?be?so?universal,?the?standard?behaviour?is?always?the?fallback?when?alternatives?are?not?usable.?There?are?also?optimizations?in?handling?the?free-list?--?for?example?storing?the?chunks?in?lists?sorted?by?sizes.?But?all?optimizations?also?have?their?own?limitations.
首先malloc/free()的操作取決于操作系統(tǒng)和編譯器的實現(xiàn)。一般來說當(dāng)你調(diào)用malloc(),系統(tǒng)會從堆中給你分配一塊足夠大的空閑內(nèi)存,并返回指向它的指針,并且標(biāo)記它不再空閑。當(dāng)調(diào)用free(),系統(tǒng)檢查這塊內(nèi)存的大小,并把它加入到free列表中,而不是立即回收它的內(nèi)存,因此操作系統(tǒng)只能處理特定大小且連續(xù)的內(nèi)存塊:一般來說是512Bytes的倍數(shù)。Free內(nèi)存塊鏈表的另一個作用是,當(dāng)調(diào)用malloc()時,系統(tǒng)會首先從這個表中查找符合要求的內(nèi)存塊,如果找不到適合大小的內(nèi)存塊再向操作系統(tǒng)申請新的內(nèi)存空間。
總結(jié)
以上是生活随笔為你收集整理的malloc申请得到的内存后,再free释放它的时候,操作系统会立即收回那块内存吗?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 遍历Linux kernel的链表时删除
- 下一篇: 一次“内存泄露”引发的血案