Datasheet

struggled with this section, you may want to obtain one of the fine introductory C++ books mentioned
in Appendix D before continuing.
Diving Deeper into C++
Loops, variables, and conditionals are terrific building blocks, but there is much more to learn. The top-
ics covered next include many features that are designed to help C++ programmers with their code as
well as a few features that are often more confusing than helpful. If you are a C programmer with little
C++ experience, you should read this section carefully.
Pointers and Dynamic Memory
Dynamic memory allows you to build programs with data that is not of fixed size at compile time. Most
nontrivial programs make use of dynamic memory in some form.
The Stack and the Heap
Memory in your C++ application is divided into two parts the stack and the heap. One way to visual-
ize the stack is as a deck of cards. The current top card represents the current scope of the program, usu-
ally the function that is currently being executed. All variables declared inside the current function will
take up memory in the top stack frame, the top card of the deck. If the current function, which we’ll call
foo() calls another function bar(), a new card is put on the deck so that bar() has its own stack frame
to work with. Any parameters passed from
foo() to bar() are copied from the foo() stack frame into
the
bar() stack frame. The mechanics of parameter passing and stack frames are covered in Chapter 13.
Figure 1-2 shows what the stack might look like during the execution of a hypothetical function
foo()
that has declared two integer values.
Figure 1-2
Stack frames are nice because they provide an isolated memory workspace for each function. If a vari-
able is declared inside the
foo() stack frame, calling the bar() function won’t change it unless you
specifically tell it to. Also, when the
foo() function is done running, the stack frame goes away, and all
of the variables declared within the function no longer take up memory.
The heap is an area of memory that is completely independent of the current function or stack frame.
You can put variables on the heap if you want them to exist even when the function in which they were
declared has completed. The heap is less structured than the stack. You can think of it as just a pile of
bits. Your program can add new bits to the pile at any time or modify bits that are already in the pile.
int i
int j
7
11
foo()
main()
18
Chapter 1
04_574841 ch01.qxd 12/15/04 3:39 PM Page 18