(^52) | Chapter 3: Patterns and Domains
As a program executes, by calling and returning from functions, the execution
Stack grows and shrinks. All memory stored on the Stack is thus reclaimed auto-
matically. However, memory stored in the Heap is under control of the
programmer and will only be released explicitly. In most cases, when a program fails
to release the memory, it may yet continue to function properly (when the program
terminates, the memory that it used is reclaimed by the operating system).
A program can run out of Heap space (although typically this is a sign of a serious
defect) if the Heap grows so large that it risks interfering with the execution Stack.
Consider the program in Example 3-3, which repeatedly generates new allocated
strings in memory.
Themallocinvocation requests a fixed set of memory (in bytes) from the
memory allocation system. If there is sufficient Heap space, the address of the
allocated memory is returned to the programmer (otherwise the null address
0x0 is returned). In the example, no attempt is made to release memory, and
after 356,331,411 iterations, the program was manually terminated.Since each
int main (int argc, char argv) {
return f(0);
}
Example 3-3. Code with memory leak
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/ Return string "abcdef" as "fabcde". /
char cycle (char s) {
int n = strlen(s);
char *u = malloc (n+1);
strncpy (u, s+1, n-1);
u[n-1] = s[0];
u[n] = '\0';
return u;
}
int main (int argc, char *argv) {
char s = strdup ("ThisStringHas25Characters");
int num=0;
for (;;) {
printf ("%d\n", ++num);
s = cycle(s);
}
}
- Be careful when executing this code on a shared machine, because it will temporarily consume all
CPU and operating system resources until the program eventually terminates.
Example 3-2. Code exhibiting infinite recursion (continued)
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