Algorithms in a Nutshell

(Tina Meador) #1

(^50) | Chapter 3: Patterns and Domains
Manual Memory Allocation
Most modern programming languages allow the programmer to allocate dynamic
memory from the Heap (as opposed to the Stack) during the execution of a
program. Consider the C program in Example 3-1.
When the program executes, variables that are local to a function (such asargc,
andargvformain) are assigned to locations on the Execution Stack, which stores
the progress of the program execution. Dynamically allocated memory (such asar1
inmain) is instead stored on the Heap, a separate region of memory available for
allocation. The address of the variable determines where the memory can be found.
In the example, one possible assignment of variables (on a Linux i686) is shown in
Table 3-5.
Table 3-4. Performance computations of 10,000,000 operations
Operation
Linux i686
(time in seconds)
Sparc Ultra-2
(time in seconds)
High-end computer
(time in seconds)
32-bit integer CMP 0.0337 0.811 0.0553
32-bit integer MUL 0.0421 2.372 0.0723
32-bit float MUL 0.1032 1.236 0.0666
64-bit double MUL 0.1028 1.406 0.0864
32-bit float DIV 0.1814 1.657 0.0768
64-bit double DIV 0.1813 2.172 0.1005
128-bit double MUL 0.2765 36.891 0.2447
32-bit integer DIV 0.2468 3.104 0.3061
32-bit double SQRT 0.2749 3.184 0.2414
Example 3-1. Sample program that allocates memory
#include <stdlib.h>
#include <string.h>
void f(char *inner) {
char temp[11];
strcpy (temp, "algorithms");
int i;
for (i=0; i<11; i++) {
inner[i] = temp[i];
}
}
int main (int argc, char *argv) {
char
ar1 = malloc(132);
char *ar2 = malloc(132);
int i = 17, j;
f (ar2);
return 0;
}
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

Free download pdf