Lecture Notes for Introduction to Computer Science II

9 August 2001 - Dynamic Memory


  1. what it is

    1. free space left over after code + data is loaded

    2. the free space is shared between the stack and the heap

      1. every free memory location belongs to either the stack or the heap, but not both

      2. the more stack, the less heap, and vice versa

      3. your free space may vary

  2. why is it useful

    1. create values at run-time, rather than program writing time

    2. handle dynamic amounts of data without waste

    3. offer virtually unlimited data storage

  3. how to get some - new and delete

    1. unlike most modern programming languages, c++ forces you to deal with all aspects of managing dynamic memory

    2. new T allocates enough heap space to hold a value of type T

      1. returns a pointer of type T * to the value

      2. the allocated space contains garbage

      3. can initialize the allocated space with val by using new T(val)

        1. string * sp = new string("hello world!");

    3. delete ptr deallocates the memory allocated by new

      1. once memory is deallocated, all pointers to it are invalid

    4. if new allocates it, delete should deallocate it

    5. if delete deallocates it, it must have been allocated by new

  4. how it goes wrong - freeing too early, or too many times, or not at all

    1. dangling pointers - ip = jp; free(jp); *ip = 3;

    2. garbage - { int ip = new int; }

    3. over deleting - ip = jp; free(jp); free(ip);

    4. deleting garbage - int * ip; free(ip);

    5. dynamic memory doesn't obey scope - it doesn't disappear when its scope does

    6. these errors are not necessarily immediately fatal - it may take time

    7. a good rule of thumb - if you new it, delete it too.

  5. dynamic memory and objects

    1. allocate object values like any other value

      1. new followed by a constructor call

      2. the default constructor can be called without parenthesis

    2. deallocate objects like any other

    3. pointers inside of objects

      1. what's the problem - pointer values don't disappear when object values do

      2. what's the solution - the opposite of constructors; something that's called when an object value disappears

      3. destructor ~class-name() { . . . }

        1. no return value; no arguments; can't be overloaded

        2. called automatically when object values fall out of scope or are deleted

        3. do not call destructors explicitly


This page last modified on 6 August 2001.