Manual Memory Allocation | 51
Patterns and
Domains
Note how the address values are all near one another, signifying that they are co-
located. The address of*main.ar1is drawn from the Heap. In the traditional
computational paradigm, the Stack grows “downward” in memory, while the
Heap grows “upward” as shown in Figure 3-4.
The addresses reveal this behavior since the computation proceeds frommain()to
f( )and the addresses of the variables steadily decrease. If the Stack grows too
large, a program crashes because the memory for the individual stack frames will
overwrite memory that should be safely protected in the heap. When this cross-
over occurs depends upon the hardware platform and the initial memory allocated
for the operating system process.
In Example 3-2, the infinite recursion caused a “Segmentation Fault” at the
393,060threcursive call, after the execution Stack had grown to over 12,577,888
bytes in size.
Table 3-5. Addresses for symbols and variables
f variables Addresses main variables Addresses Global symbols Addresses
f.inner 3221222728 main.argc 3221222796 &f 4195576
f.temp 3221222704 main.argv 3221222784 &main 4195648
f.i 3221222700 main.ar1 3221222776
main.ar2 3221222768
main.i 3221222764
main.j 3221222760
*main.ar1 5246992
*main.ar2 5247136
Figure 3-4. Stack and Heap dynamic behavior
Example 3-2. Code exhibiting infinite recursion
#include <stdio.h>
int f(int n) {
printf (" n %d[%u] \n", n, &n);
return f(n+1);
}
Algorithms in a Nutshell
Algorithms in a Nutshell By Gary Pollice, George T. Heineman, Stanley Selkow ISBN:
9780596516246 Publisher: O'Reilly Media, Inc.
Prepared for Ming Yi, Safari ID: [email protected]
Licensed by Ming Yi
Print Publication Date: 2008/10/21 User number: 594243
© 2009 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use