CS242N Lecture 2 Adam Mitz mitzcse'wustl'edu Dept' of Computer Science and Engineering Washington Un - PowerPoint PPT Presentation

1 / 27
About This Presentation
Title:

CS242N Lecture 2 Adam Mitz mitzcse'wustl'edu Dept' of Computer Science and Engineering Washington Un

Description:

A pointer can point to heap or stack memory or static (global) memory ... an object on the heap. The object will remain on the heap until the program says ... – PowerPoint PPT presentation

Number of Views:12
Avg rating:3.0/5.0
Slides: 28
Provided by: adam3
Category:

less

Transcript and Presenter's Notes

Title: CS242N Lecture 2 Adam Mitz mitzcse'wustl'edu Dept' of Computer Science and Engineering Washington Un


1
CS242N Lecture 2Adam Mitz (mitz_at_cse.wustl.edu)
Dept. of Computer Science and EngineeringWashingt
on University in St. Louis
  • Memory Management in C
  • And related issues

2
Goals for Today
  • Review last week, demo debugger
  • Pointers and References, the whole story
  • Arrays
  • Heap memory vs. Stack memory
  • How to use
  • Common problems
  • const

3
Review of Last Weeks Lecture
  • Tools
  • Unix, emacs, gcc, make, gdb, ddd
  • C Program Structure
  • .H file .cc file Class Implementation
  • main.cc
  • What to include when, using forward declaration
    of classes
  • C Class Structure
  • Canonical Form (dtor, copy ctor, etc.)
  • Debug mode output

4
ddd Demo
  • Running the stack program in the ddd debugger
    to peek at data structures.
  • ddd Data Display Debugger

5
Syntactical Differences Review
  • Scope Resolution Operator ()
  • Operator overloading (operator)
  • Pointer and Reference Syntax (, )
  • Arrow shortcut (ptr-gtFunction())
  • Initializer Lists for Ctors ()
  • Destructor ()
  • const
  • NULL and bool
  • this is a pointer

6
Pointer and Reference Syntax
  • When declaring a variables type (includes
    function signatures)
  • int x //x is a pointer to an integer
  • int y a //y is a reference to (alias of)
    variable a
  • When using a variables value in an expression
  • cout ltlt (b) //print what b points to
  • cout ltlt (c) //print cs addresss
  • The int/int syntax above is legal but not
    conventional.
  • Many programmers use int x
  • I highly recommend you do not. Its much easier
    to understand int x, right? (Caveat char a,
    b)

7
What is a pointer?
  • A pointer is a variable that holds a number.
    This number is interpreted as the address of some
    other data (or NULL).
  • Pointers can be thought of as variables that have
    type Foo (Pointer to Foo) where Foo is the
    type of data that it points to (base type)
  • Any variable can be a pointer, including
    parameters and return types

8
Properties of Pointers
  • The base type of the pointer can be any type at
    all in the program, even another pointer (i.e.
    int)
  • C does not check to see that a pointer points
    to NULL or to a valid piece of data of the base
    type
  • A pointer can point to heap or stack memory or
    static (global) memory
  • A pointer to anything is written as void
    (analogous to Object in Java)

9
More pointers on pointers
  • Pointers to functions also exist in C/C.
    Hopefully youll never have to use them.
  • Arrays and pointers are closely related. The
    operator is defined as adding an offset to the
    pointer, then dereferencing. No bounds checking
    is done.
  • Pointers are the only form of indirection in C
    (references were added to C).

10
What is a reference?
  • Do not confuse a C reference with a Java
    reference.
  • A reference is another method of indirection.
    References are aliases of actual objects, instead
    of addresses telling us where they live
    (pointers).
  • References are not first class.
  • References can never be NULL.
  • A reference variable can never be re-assigned to
    refer to another object.

11
Reference Use
  • References are useful in passing parameters and
    returning data from functions.
  • Think of a reference as a pointer that
    automatically has the value of the pointed-to
    object when its used.
  • There is no such thing as a reference to a
    reference or a ptr to a ref.
  • There is such thing as a reference to a pointer.
    (Pointers are 1st class.)

12
Aliasing vs. Pointing
  • Make an object
  • Foo p1(1, 2)
  • Aliasing (References)
  • Foo ref p1 //note type of RHS is
    Foo, but no
  • Pointing // copy is done by this
    assignment
  • Foo ptr p1 //note type of RHS is
    Foo
  • ref and ptr serve the same purpose, they make it
    possible for us to refer to the object by a name
    other than p1.
  • The ref variable acts just like an actual Foo
    object. It should be though of as having class
    Foo.
  • The ptr variable acts like a pointer. It
    should be thought of as having class Foo.

13
Aliasing vs. Pointing Continued
  • In an expression, p1, ref, and ptr have the same
    type and can be used in the same manner.
  • They point at the same memory so the following
    values (memory addresses) should be equal
  • p1
  • ref
  • ptr

14
Use of References in Parameter Passing
  • By value
  • void increment(int i) i
  • Doesnt work. is new value is thrown out.
    int i3 increment(i) coutltlti //still 3, doh!
  • By reference
  • void increment(int i) i
  • Actually works with no change of syntax in caller
    or method body of called function!
  • Thus references let us modify objects passes as
    parameters to functions. Use judiciously.
  • This can also be done with pointers but the
    syntax is uglier.

15
By reference for efficiency
  • Even if we dont need to modify parameters,
    passing by reference can be good in many cases
    for efficiency.
  • void Print(const BinaryTree t)
  • Without the copy constructor for BinaryTree is
    called implicitly, most likely causing a deep
    copy of all elements in the data structure.
  • const is used to indicate read-only
  • The Print method can only call const methods on
    the BinaryTree, and can not assign to its
    instance variables.

16
Returning a reference
  • Factory Method example
  • Foo makeMeAnotherFoo(int i)
  • Since the method creates an object, it needs to
    pass that object back to the caller.
  • By-value doesnt work since the local value is
    going away when the method exits.
  • By-reference makes it easy and syntactically
    nice. (By pointer is also possible.)

17
Assignment Operator Example
  • Both the parameter and the return type are by
    reference
  • Stack Stackoperator(const Stack s)
  • //copy data from s into instance vars
  • return this
  • Use s4 s3 s2 s1
  • Why is a reference REQUIRED for the parameter of
    the copy constructor?

18
C Memory Model
  • Stack
  • All variables that are declared in a statement
    inside a function are allocated space on the call
    stack.
  • The size of each functions stack frame must be
    bounded and compile-time determinable (in most
    cases).
  • Heap
  • Due to these restrictions, there are some things
    we cant do on the stack.
  • Runtime dynamic structures and unbounded
    structures must live on the heap.

19
Syntax for heap use
  • Foo f new Foo(1, 2)
  • f is a pointer variable on the stack
  • f points to an object on the heap
  • The object will remain on the heap until the
    program says otherwise, even when f goes out of
    scope.
  • delete f
  • f is still around but it no longer points to a
    valid object.

20
Performance Comparison
  • Allocating memory with new takes time
  • void slow()
  • double x new double
  • x 7.3
  • double y new double
  • y sin(x)
  • delete x
  • delete y
  • void fast()
  • double x, y
  • x 7.3
  • y sin(x)
  • Therefore use new only when absolutely necessary

21
Use with arrays
  • Foo fa new Foo35
  • fa is a 35-element array of Foos. Each object in
    the array has been constructed with the default
    constructor.
  • delete fa //note special syntax for array
    deletion
  • Remember pointer and array relationship

22
Using new and delete with Classes
  • new and delete lend themselves nicely to
    constructor and destructor use, but be sure you
    really need heap memory for this classs objects
  • Assignment operator, copy constructor, other
    factory methods can new without delete.
  • Its then the callers job to make sure the heap
    memory is deleted when its appropriate to do so.

23
Common Memory Problems
  • Invalid array subscript
  • double a3, b
  • a3 7.0 //b is now 7.0
  • Returning a ref/ptr to a local
  • Foo bad() Foo x return x
  • Compiler will warn even without Wall
  • Writing memory thats not yours
  • (a sizeof(void) ) 3.0

24
More Common Memory Problems
  • Pass by Value when modifications are to be made.
  • void updateFoo(Foo f)
  • One makes a big difference!
  • Wild pointer (also see example)
  • double s //what does s point to?
  • s 10.0
  • Memory leak (lifetime problems)

25
Memory Use Tips
  • Bounds-check your arrays (write a class or use
    one)
  • Always initialize your variables, pointers and
    objects when they are declared
  • Watch out for pointers that are relative to other
    pointers. The first pointer could change.
    (Array example)
  • Use const
  • Always declare assignment operators and copy
    constructors
  • Use new only when its really needed

26
const
  • const is a modifier that indicates something is
    unchangeable
  • It can be applied to
  • Variables, like final in Java
  • Parameters, especially useful with references
  • Methods, indicating the method will not change
    any member variables
  • Pointers can be const in 3 ways
  • const Foo ptr //the target cant change
  • Foo const ptr //ptr itself cant change
  • const Foo const ptr //both

27
Conclusions
  • Be careful! (But not cautious)
  • Small changes in syntax can change the program in
    big ways.
  • Read your program aloud in English
  • Assign the value of the pointer
  • Assign the object pointed-to
  • Make conscious decisions
  • Who owns this object?
  • Should I use a pointer or a reference?
  • Should I use stack or heap memory?
Write a Comment
User Comments (0)
About PowerShow.com