Lecture Notes for Introduction to Computer Science II
9 August 2001 - Dynamic Memory
- what it is
- free space left over after code + data is loaded
- the free space is shared between the stack and the heap
- every free memory location belongs to either the stack or the heap,
but not both
- the more stack, the less heap, and vice versa
- your free space may vary
- why is it useful
- create values at run-time, rather than program writing time
- handle dynamic amounts of data without waste
- offer virtually unlimited data storage
- how to get some - new and delete
- unlike most modern programming languages, c++ forces you to deal with
all aspects of managing dynamic memory
-
new
T allocates enough heap space to hold a value of type
T
- returns a pointer of type T
*
to the value
- the allocated space contains garbage
- can initialize the allocated space with val by using
new
T(
val)
-
string * sp = new string("hello world!");
-
delete
ptr deallocates the memory allocated by new
- once memory is deallocated, all pointers to it are invalid
- if
new
allocates it, delete
should deallocate it
- if
delete
deallocates it, it must have been allocated by new
- how it goes wrong - freeing too early, or too many times, or not at all
- dangling pointers -
ip = jp; free(jp); *ip = 3;
- garbage -
{ int ip = new int; }
- over deleting -
ip = jp; free(jp); free(ip);
- deleting garbage -
int * ip; free(ip);
- dynamic memory doesn't obey scope - it doesn't disappear when its scope
does
- these errors are not necessarily immediately fatal - it may take time
- a good rule of thumb - if you new it, delete it too.
- dynamic memory and objects
- allocate object values like any other value
-
new
followed by a constructor call
- the default constructor can be called without parenthesis
- deallocate objects like any other
- pointers inside of objects
- what's the problem - pointer values don't disappear when object
values do
- what's the solution - the opposite of constructors; something that's
called when an object value disappears
- destructor
~
class-name() { . . . }
- no return value; no arguments; can't be overloaded
- called automatically when object values fall out of scope or are
deleted
- do not call destructors explicitly
This page last modified on 6 August 2001.