23
CS 210 CS 210 Lecture 3 : Dynamic memory and pointers Data Structures

CS 210 Lecture 3 : Dynamic memory and pointers

Embed Size (px)

DESCRIPTION

CS 210 Lecture 3 : Dynamic memory and pointers. Data Structures. Why Dynamic Memory Allocation?. No need to know in advance the size of the data structure. No memory needlessly allocated. Your limit is the computer ’ s memory limit. Automatic objects E.g. int i; float j; - PowerPoint PPT Presentation

Citation preview

Page 1: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

CS 210Lecture 3 : Dynamic memory and pointers

Data Structures

Page 2: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

Why Dynamic Memory Allocation?

No need to know in advance the size of the data structure.

No memory needlessly allocated. Your limit is the computer’s

memory limit.

Page 3: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

Automatic Vs. Dynamic Objects

Automatic objects E.g. int i; float j; Space allocated

during compile time and will remain as long as object is within scope.

Compiler de-allocates space as soon as object goes out of scope.

Dynamic objects Objects not assigned

name while program is written and thus are only accessible via pointers.

Allocation/de-allocation entirely managed by the programmer and is performed during runtime.

Page 4: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

Declaring a pointer A pointer is a variable that can store the

memory address of some piece of data.

Declaring a pointer:float *p;

p is a pointer that can store a memory address of a floating point variable.

Page 5: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

Declaring a pointer does not automatically give it a valid memory address:

float *p;

To allocate memory, use the key word: new

p = new float;

This is dynamic allocation of memory.

Allocating memory

p

p ?

Page 6: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

The Memory HeapC++ maintains a storage pool of available memory called the heap. The keyword new allocates memory from this storage pool.

p = new float;

1000

1001

1002

1003

1004

2000

. . .

Heap

p

1000

1001

1002

1003

1004

2000

. . .

Heap

p

Page 7: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

Returning memory to the heap

Use the keyword, delete, to return memory to the heap:

delete p;

p no longer points to a valid memory location (p is now undefined)

The memory is returned to the heap and can be reallocated later.

After deleting a pointer, it should always be reset to NULL.

Page 8: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

De-referencing PointersTo access the memory pointed to by a pointer, use the indirection operator (*):

*p = 15.5;

Example:float *p;p = new float;*p = 15.5;cout << "The contents of memory cell pointed to by p is " << *p << endl;delete p;

p 15.5

Page 9: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

Watch Out!

Dereferencing un initialized pointers not only may alter other important data, or even destroy some other parts of memory, but even worst, this type of accidental error may run silently without causing any compilation or runtime errors that might signal it. So, it is a difficult-to-find error.

int *random_pointer;

Page 10: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

General form for pointers

Declaration of a pointer:type *pointerName;

Allocation of memory:new type

ornew type[n] //allocates n elements of specified type

Accessing data with pointer:

*pointerName

Page 11: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

Illegal Pointer operationsBecause pointers hold addresses, you cannot assign data of type int or float or other data types to a pointer. The following is not allowed:

int *p;float *q;

p = 1000; // Not Allowedq = 15.5; // Not Allowed

Page 12: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

Assigning a pointerOne pointer can be assigned to another of the same type:

int *p;int *q;

p = new int;q = p;*p = 20;cout << *p << " " << *q << endl;

p 20

q

Page 13: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

Recall Arrays

int numbers[5];

The name of the array, numbers, contains the base address of the array.

numbers, is a pointer.

Page 14: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

Dynamically Allocated Arraysint size,* dynamic_array, i;

cout<<“Enter an array size: “<< flush;cin>> size;dynamic_array= new int [size];for (i=0;i<size; i++) dynamic_array[i]=i;delete []dynamic_array;

Page 15: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

Pointer arithmetic

Pointer arithmetic allows accessing of items in an array:

int *p, *q;p = new int[5];q=p+2;q++;

*p is value of p[0]*(p+i) is value of p[i]

Each increment of p moves the pointer by enough memory to move to next item in the array.

Page 16: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

Pointer variables can be used to access automatic objects as well.

This creates an alias for the automatic variable and should be carefully managed, even better, avoided.

Example:char alpha;char *char_ptr;char_ptr = & alph;

Addresses of automatic objects

alpha

char_ptr alpha

Page 17: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

Pointers to structsPointers to structs follow the same rules:

struct money {int dollars;int cents;

};

money *p;p = new money;

p ? ?dollars cents

Page 18: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

Accessing struct membersStruct members are accessed with the selection operator:

p = new money;(*p) . dollars = 10000; //The parentheses are essential!(*p) . cents = 50;

Alternatively:p -> dollars = 10000;p -> cents = 50;

p 10000 50dollars cents

Page 19: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

orphan structsIf you assign one pointer to another, the struct previously pointed to by the latter is no longer accessible:

p 6947 25dollars cents

q 6947 40dollars cents

Consider p and q:

Page 20: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

orphan structsIf you assign one pointer to another, the struct previously pointed to by the latter is no longer accessible:

p 6947 25dollars cents

q 6947 40dollars cents

q = p;

Page 21: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

Things to be careful aboutWARNINGS: If more than one pointer points to the same structure, if one is deleted, the other may still point to that location. However, C++ may reassign that memory, causing errors in the program execution.

Make sure you no longer need a structure before you return it to the heap.

Only use delete with pointers whose values were set by new.

Page 22: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

Diagram each linestruct electric {

String20 current;int volts;

};electric *p, *q;

p = new electric;strcpy( p - > current, "AC" );p - > volts = 220;

q = new electric;q -> volts = p - > volts;strcpy ( q - > current, "DC");

Page 23: CS 210 Lecture 3 : Dynamic memory and pointers

CS 210

Diagram the pointers

electric *a, *b, *c;a = new electric;b = new electric;c = new electric;

a = b;

b = c;

c = a;