Docsity

Lecture Notes on Dynamic Memory - Data Structures | CSCI 1200, Study notes of Data Structures and Algorithms

Toggle sidebar
bg1
CSCI-1200 Computer Science II — Fall 2006
Lecture 16 — Dynamic Memory
Review from Lecture 15
•Pointer variables, arrays, character arrays, pointers as array iterators, and calling conventions.
Today’s Lecture — Pointers and Dynamic Memory
•K & M rest of Chapter 10; Malik, 753-781
•Arrays and pointers, different types of memory, and dynamic allocation of arrays.
16.1 Three Types of Memory
•Automatic memory: memory allocation inside a function when you create a variable. This
allocates space for local variables in functions (on the stack) and deallocates it when variables
go out of scope. For example:
int x;
double y;
•Static memory: variables allocated statically (with the keyword static). They are are not
eliminated when they go out of scope. They retain their values, but are only accessible within
the scope where they are defined.
static int counter;
•Dynamic memory: explicitly allocated (on the heap) as needed. This is our focus for today.
16.2 Dynamic Memory
•Dynamic memory is:
–created using the new operator,
–accessed through pointers, and
–removed through the delete operator.
•Here’s a simple example involving dynamic allocation of integers:
int * p = new int;
*p = 17;
cout << *p << endl;
int * q;
q = new int;
*q = *p;
*p = 27;
cout << *p << " " << *q << endl;
int * temp = q;
q = p;
p = temp;
cout << *p << " " << *q << endl;
delete p;
delete q;
heapstack
p
q
temp
17
•The expression new int asks the system for a new chunk of memory (from the heap) that
is large enough to hold an integer and returns the address of that memory. Therefore, the
statement int * p = new int; allocates memory from the heap and stores its address in
the pointer variable p. The variable pis placed on the stack as discussed last lecture.
pf3
pf4

Partial preview of the text

Download Lecture Notes on Dynamic Memory - Data Structures | CSCI 1200 and more Study notes Data Structures and Algorithms in PDF only on Docsity!

CSCI-1200 Computer Science II — Fall 2006

Lecture 16 — Dynamic Memory

Review from Lecture 15

  • Pointer variables, arrays, character arrays, pointers as array iterators, and calling conventions.

Today’s Lecture — Pointers and Dynamic Memory

  • K & M rest of Chapter 10; Malik, 753-
  • Arrays and pointers, different types of memory, and dynamic allocation of arrays.

16.1 Three Types of Memory

  • Automatic memory: memory allocation inside a function when you create a variable. This allocates space for local variables in functions (on the stack) and deallocates it when variables go out of scope. For example: int x; double y;
  • Static memory: variables allocated statically (with the keyword static). They are are not eliminated when they go out of scope. They retain their values, but are only accessible within the scope where they are defined. static int counter;
  • Dynamic memory: explicitly allocated (on the heap) as needed. This is our focus for today.

16.2 Dynamic Memory

  • Dynamic memory is:
    • created using the new operator,
    • accessed through pointers, and
    • removed through the delete operator.
  • Here’s a simple example involving dynamic allocation of integers:

int * p = new int; *p = 17; cout << *p << endl; int * q; q = new int; *q = *p; *p = 27; cout << *p << " " << *q << endl; int * temp = q; q = p; p = temp; cout << *p << " " << *q << endl; delete p; delete q;

stack heap

p

q

temp

  • The expression new int asks the system for a new chunk of memory (from the heap) that is large enough to hold an integer and returns the address of that memory. Therefore, the statement int * p = new int; allocates memory from the heap and stores its address in the pointer variable p. The variable p is placed on the stack as discussed last lecture.
  • The statement delete p; takes the integer memory pointed by p and returns it to the system for re-use.
  • In between the new and delete statements, the memory is treated just like memory for an ordinary variable, except the only way to access it is through pointers. Hence, the manipulation of pointer variables and values is similar to the examples covered in Lecture 15 except that there is no explicitly named variable other than the pointer variable.
  • Dynamic allocation of primitives like ints and doubles is not very interesting or significant. What’s more important is dynamic allocation of arrays and objects.

16.3 Exercise

  • What’s the output of the following code? Be sure to draw a picture to help you figure it out.

double * p = new double; *p = 35.1; double * q = p; cout << *p << " " << *q << endl; p = new double; *p = 27.1; cout << *p << " " << *q << endl; *q = 12.5; cout << *p << " " << *q << endl; delete p; delete q;

16.4 Dynamic Allocation of Arrays

  • Declaring the size of an array at compile time doesn’t offer much flexibility. Instead we can dynamically allocate an array based on data. This gets us part-way toward the behavior of the standard library vector class. Here’s an example:

int main() { cout << "Enter the size of the array: "; int n,i; cin >> n; double *a = new double[ n ]; for ( i=0; i<n; ++i ) a[i] = sqrt( i ); for ( i=0; i<n; ++i ) if ( double(int(a[i])) == a[i] ) cout << i << " is a perfect square " << endl; delete [] a; return 0; }

i

stack heap

n

a

  • Consider the line: double *a = new double[ n ];
    • The expression new double[ n ] asks the system to dynamically allocate enough consec- utive memory to hold n double’s (usually 8n bytes).
    • What’s crucially important is that n is a variable. Therefore, its value and, as a result, the size of the array are not known until the program is executed. When this happens, the memory must be allocated dynamically.
    • The address of the start of the allocated memory is assigned to the pointer variable a.
  • After this, a is treated as though it is an array. For example: a[i] = sqrt( i ); In fact, the expression a[i] is exactly equivalent to the pointer arithmetic and dereferencing expression *(a+i) which we have seen several times before.

16.7 Dynamic Allocation Example: The Sieve of Eratosthenes, Revisited

  • We return to the problem of finding all primes. The first time we did this we used a list. Now we use a dynamically allocated array:

// Using Sieve of Eratostenes determine all prime numbersless than or // equal to an integer provided on the command line. #include #include #include using namespace std;

int main(int argc, char* argv[]) { // Check usage. Take n from the 1st argument. Make sure it is positive. if (argc != 2) { cerr << "Usage:\n " << argv[0] << " n\n" << "where n is a positive integer\n"; return 0; } int n = atoi(argv[1]); if (n <= 0) { cerr << "Usage:\n " << argv[0] << " n\n" << "where n is a positive integer\n"; return 0; }

// Create and initialize a dynamically allocated array bool * is_prime_sieve; is_prime_sieve = new bool[n+1]; int i; is_prime_sieve[0] = is_prime_sieve[1] = false; for (i=2; i<=n; ++i) is_prime_sieve[i] = true;

// Check each integer up to n to see if it is prime. Output those that are. int prime_count = 0; for (i = 2; i <= n ; ++i) { // If a number is not prime, then we can skip it. if (is_prime_sieve[i]) { cout << i << " is prime\n"; ++prime_count; // No multiples of i are prime. Mark these multiples in the array. for (int j = 2*i; j <= n; j += i) is_prime_sieve[j] = false; } } cout << "\nThere are " << prime_count << " primes <= " << n << endl;

// Release the dynamic memory through the delete operator delete [] is_prime_sieve; return 0; }

  • Once n is taken from the command-line, we define a bool pointer and then make it point to the start of a dynamically-allocated array of bools. Each entry from 0 to n is used to indicate whether or not the index value is prime.
  • After this, is prime sieve is treated like an ordinary array.
  • The dynamic memory is deleted at the end.

16.8 Exercise: Dynamic Allocation Arrays vs. Vectors

  • Rewrite the previous example using vectors instead of arrays.