Professional Documents
Culture Documents
Memory Management - Part I: Problem
Memory Management - Part I: Problem
Difficulty: 3 / 10
This GotW covers basics about C++'s main distinct memory stores. The following
problem attacks some deeper memory-management questions in more detail.
Problem
C++ has several distinct memory areas where objects and non-object values may be
stored, and each area has different characteristics.
Name as many of the distinct memory areas as you can. For each, summarize its
performance characteristics and describe the lifetime of objects stored there.
Example: The stack stores automatic variables, including both builtins and objects of
class type.
Solution
The following summarizes a C++ program's major distinct memory areas. Note that
some of the names (e.g., "heap") do not appear as such in the draft [standard].
Memory Area
--------------
Const Data
Stack
Heap
Global/Static
Note about Heap vs. Free Store: We distinguish between "heap" and "free store"
because the draft deliberately leaves unspecified the question of whether these two
areas are related. For example, when memory is deallocated via operator delete,
18.4.1.1 states:
It is unspecified under what conditions part or all of such reclaimed storage is allocated
by a subsequent call to operator new or any of calloc, malloc, or realloc, declared in
<cstdlib>.
Similarly, it is unspecified whether new/delete is implemented in terms of malloc/free or
vice versa in a given implementation. Effectively, the two areas behave differently and
are accessed differently -- so be sure to use them differently!
Trong lao ng ngi ta phn thnh lao ng chn tay v lao ng tr c . Th trong C++ cng
vy, ngi ta c th dng cch C++ s dng memory phn loi memory , nhng ci cng
loi th c xp vo cng vng d qun l .
Ni mt cch k thut (technical), C++ chia memory thnh nhiu vng (area), mi vng c
nhng c im ring ca n . Cc vng nh sau :
2. Vng Stack : cha cc bin automatic (bin local) hoc cha cc i s khi gi
function . Cp pht trong vng Stack th nhanh hn cp pht "ng" (xem Free Store v
Heap di)
3. Vng Free Store : dng cp pht memory "ng" thng qua new/delete
5. Vng Global/Staic : dng cha cc bin static, global .... "c tnh ton v cp
pht 1 ln, ngay khi khi ng chng trnh, v gi nguyn trong sut thi gian chng
trnh chy, nh vy c nhc im l nu kch thc ln qu s chim dng nhiu b nh
h thng => bn khng ch ng b bt i c nu khng cn n na, n ch b xa b
khi chng trnh kt thc, v th chng trnh ca bn nn c b nh tnh cng nh cng
tt, ch khai bo trong b nh tnh nhng ci cn thit." ( nh et cp trong bi vit
pha di)
Vi 2 vng "Free Store" + "Heap", "bn cp pht n khi chng trnh ang chy, c th loi b
n khi cn, cho php bn ch ng qun l b nh, nhng c nhc im l nu bn "qun"
khng loi b n s c nguy c r r b nh v thm ch nh hng n ton b h thng." (et)