Docsity

Pointers and Dynamic Memory in Computer Science II - CSci 1200 Lecture 6, Study notes of Data Structures and Algorithms

Toggle sidebar
bg1
Computer Science II — CSci 1200
Lecture 6
Pointers, Dynamic Memory
Review from Lecture 5
•Pointer variables
•Arrays
•Pointer arithmetic and dereferencing
Today’s Lecture — Pointers and Dynamic Memory
•Arrays and pointers
•Different types of memory
•Dynamic allocation of arrays
•Examples and applications
Aside: Sorting an Array
•Arrays may sorted using std::sort, just as vectors may. Pointers are used in place
of iterators. For example, if ais an array of doubles and there are nvalues in the
array, then
std::sort( a, a+n )
sorts the values in the array into increasing order.
•Remember the variable astores a pointer to a double — it just happens to be the
start of an array.
Three Types of Memory
•Automatic memory: memory allocation inside a function when you create a variable.
For example:
int x;
double y;
–This allocates space for local variables in functions and eliminates it when vari-
ables go out of scope.
–This memory is allocated on the stack. The compiler knows exactly where to put
each variable on the stack (relative to the start of the scope).
•Static memory: variables allocated statically, as in
static int x;
pf3
pf4
pf5

Partial preview of the text

Download Pointers and Dynamic Memory in Computer Science II - CSci 1200 Lecture 6 and more Study notes Data Structures and Algorithms in PDF only on Docsity!

Computer Science II — CSci 1200

Lecture 6

Pointers, Dynamic Memory

Review from Lecture 5

  • Pointer variables
  • Arrays
  • Pointer arithmetic and dereferencing

Today’s Lecture — Pointers and Dynamic Memory

  • Arrays and pointers
  • Different types of memory
  • Dynamic allocation of arrays
  • Examples and applications

Aside: Sorting an Array

  • Arrays may sorted using std::sort, just as vectors may. Pointers are used in place of iterators. For example, if a is an array of doubles and there are n values in the array, then

std::sort( a, a+n )

sorts the values in the array into increasing order.

  • Remember the variable a stores a pointer to a double — it just happens to be the start of an array.

Three Types of Memory

  • Automatic memory: memory allocation inside a function when you create a variable. For example:

int x; double y;

  • This allocates space for local variables in functions and eliminates it when vari- ables go out of scope.
  • This memory is allocated on the stack. The compiler knows exactly where to put each variable on the stack (relative to the start of the scope).
  • Static memory: variables allocated statically, as in

static int x;

are not eliminated when they go out of scope. They retain their values, but are only accessible within the scope where they are defined. We will not be discussing these much.

  • Dynamic memory is explicitly allocated at run time (not compile time), and the size of the allocation can be determined at run time. - This memory is allocated on the heap. - It is the focus of today’s lecture.

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;

  • The expression new int asks the system for a new chunk of memory that is large enough to hold an integer.
  • Therefore, the statement

int * p = new int;

allocates a new chunk of memory large enough to hold an integer, and stores the memory address of the start of this memory in the pointer variable p.

  • The statement delete p; takes the integer memory pointed by p and returns it to the system for re-use.
  • This memory is allocated from and returned to a special area of memory called the heap. By contrast local variables and function parameters are allocated from a differ- ent memory area called the stack.

Exercise

What is the output of the following code? Be sure to draw a picture of the stack and the heap 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;

Dynamic Allocation of Arrays

  • Declaring the size of an array at compile time does not offer much flexibility.
  • As an alternative, we can read a variable that states the size of the desired array and then dynamically allocate. This is our first step toward developing our own implementation of a vector.
  • Here is an example:

int main() { cout << "Enter the size of the array: "; int n; cin >> n; double *a = new double[ n ];

int i; 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; }

  • Consider the line

double *a = new double[ n ];

  • The expression new double[ n ] asks the system to dynamically allocate enough consecutive 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 deref- erencing expression

*(a+i)

which we saw in Lecture 4.

  • After we are done using the array, the line

delete [] a;

releases the memory allocated for the entire array. Without the [], only the first double would be released.

  • Since the program is ending, releasing the memory is not a major concern. In more substantial programs it is ABSOLUTELY CRUCIAL.

Exercises

  1. Write code to

(a) dynamically allocate an array of n integers, (b) point to this array using the integer pointer variable a, and (c) then read n values into the array from the stream cin.

  1. Now, suppose we wanted to double the size of array a without losing the values. This requires some work.

(a) Write code to allocate an array of size 2*n, pointed to by integer pointer variable temp (which will become a). (b) Write code to copy the n values of a into the first n locations of array temp. (c) Write code to delete array a.

#include #include #include using namespace std;

int main( int argc, char* argv[] ) { // Check the number of command-line arguments if ( argc != 2 ) { cerr << "Usage:\n " << argv[0] << " n\n" << "where n is a positive integer\n"; return 0; }

// Take n from the 1st argument by converting the string to an // integer. Make sure it is positive. int n = atoi( argv[1] ); if ( n <= 0 ) { cerr << "Usage:\n " << argv[0] << " n\n" << "where n is a positive integer\n"; return 0; }

// Start here...

return 0; }