Joel Winstead CS201j: Engineering Software University of Virginia Computer Science Lecture 16: Pointers and Memory Management.

Slides:



Advertisements
Similar presentations
SPLINT STATIC CHECKING TOOL Sripriya Subramanian 10/29/2002.
Advertisements

ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
Spring 2005, Gülcihan Özdemir Dağ Lecture 12, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 12 Outline 12.1Introduction.
Agenda  Review: pointer & array  Relationship between pointer & array  Dynamic memory allocation.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Memory Allocation. Memory A memory or store is required in a computer to store programs (or information or data). Data used by the variables in a program.
Pointers Revisited l What is variable address, name, value? l What is a pointer? l How is a pointer declared? l What is address-of (reference) and dereference.
Informática II Prof. Dr. Gustavo Patiño MJ
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
CS 61C L04 C Structures, Memory Management (1) Garcia, Fall 2004 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Pointers and Arrays Beyond Chapter Pointers and Arrays What are the real differences? Pointer Holds the address of a variable Can be pointed.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
Stack and Heap Memory Stack resident variables include:
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
David Notkin Autumn 2009 CSE303 Lecture 12 October 24, 2009: Space Needle.
Technical Module : Pointers #1 2000/01Scientific Computing in OOCourse code 3C59 Technical Module : Pointers In this module we will cover Pointers to primitives.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
Object-Oriented Programming in C++
1 CS 132 Spring 2008 Chapter 3 Pointers and Array-Based Lists read p
C Programming Day 4. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to.
1 Splint: A Static Memory Leakage tool Presented By: Krishna Balasubramanian.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
ECE Application Programming
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 10 – C: the heap and manual memory management.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
1 2/2/05CS250 Introduction to Computer Science II Pointers.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
What do I need to Know For My Assignment?. C Pointer Review To declare a pointer, we use the * operator. This is similar to but different from using *
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Imperative Programming C. Imperative Programming Heart of program is assignment statements Aware that memory contains instructions and data values Commands:
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
Yan Shi CS/SE2630 Lecture Notes
Overview 4 major memory segments Key differences from Java stack
CSE 374 Programming Concepts & Tools
Introduction to Programming
Lecture 15: Using Low-Level Languages CS201j: Engineering Software
malloc(): Dynamic Memory Management
Checking Memory Management
Pointers Revisited What is variable address, name, value?
CSCI206 - Computer Organization & Programming
Dynamic Memory Allocation
Dynamic Memory Allocation
Overview 4 major memory segments Key differences from Java stack
Chapter 15 Pointers, Dynamic Data, and Reference Types
CSC215 Lecture Memory Management.
Memory Allocation CS 217.
Lecture 9: Exceptions in Java CS201j: Engineering Software
CS111 Computer Programming
Chien-Chung Shen CIS/UD
EENG212 – Algorithms & Data Structures Fall 07/08 – Lecture Notes # 5b
Pointers and Arrays Beyond Chapter 16
Lecture 18: Deep C Garbage Collection CS201j: Engineering Software
Dynamic Memory Allocation
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Dynamic Memory – A Review
Presentation transcript:

Joel Winstead CS201j: Engineering Software University of Virginia Computer Science Lecture 16: Pointers and Memory Management

Halloween 2002CS 201J Fall Menu Null Pointers in C Memory Management in C Phylogeny Revisited

Halloween 2002CS 201J Fall Pointers in C Pointers are similar to object references in Java Assigning a pointer has sharing semantics int i = 37; int *p = malloc(sizeof(int)); int *q; q = p; *p = 7; i p q 7 37

Halloween 2002CS 201J Fall Null Pointers What if a pointer doesn’t point to anything? void main(String argv[]) { Integer i = null; System.out.println(i.intValue()); } int main(int argc,char *argv[]) { int *i = NULL; printf(“i is %d\n”,*i); }

Halloween 2002CS 201J Fall Null Pointers What if a pointer doesn’t point to anything? void main(String argv[]) { Integer i = null; System.out.println(i.intValue()); } int main(int argc,char *argv[]) { int *i = NULL; printf(“i is %d\n”,*i); } Exception in thread “main” java.lang.NullPointerException at nullref.main(nullref.java:7) Behavior is undefined!

Halloween 2002CS 201J Fall Following Null Pointers The program may crash immediately The program may produce corrupted output The program may corrupt data somewhere else in the program’s memory –This results in a difficult-to-find bug The program could mail itself to everyone in your address book and cause your computer to self-destruct –The C standard does not define what should happen, so absolutely anything is legal!

Halloween 2002CS 201J Fall Splint Annotations for Pointers –A pointer guaranteed not to be null –A pointer that might be null FILE * char *filename,char *mode);

Halloween 2002CS 201J Fall Splint Warnings Splint reports a warning if: –The program dereferences a pointer without checking first –The program assigns a pointer to a variable –The program passes a pointer to a function expecting a pointer

Halloween 2002CS 201J Fall Example char firstChar( char *s) { return *s; } > splint null.c Splint null.c: (in function firstChar) null.c:3:11: Dereference of possibly null pointer s: *s null.c:1:35: Storage s may become null Finished checking code warning found

Halloween 2002CS 201J Fall Correcting the Problem char firstChar( char *s) { if (s == NULL) { fprintf(stderr,”s is null in firstChar\n”); exit(EXIT_FAILURE); } else { return *s; }

Halloween 2002CS 201J Fall Another Solution char firstChar( char *s) { return *s; }

Memory Management in C

Halloween 2002CS 201J Fall malloc Memory in C is allocated using the malloc function –This is similar in some ways to Java’s new operator We use sizeof to determine how much memory to allocate int *i = malloc(sizeof(int)); char *s = malloc(sizeof(char)*100); Species s = malloc(sizeof(*s));

Halloween 2002CS 201J Fall Creating Objects in C Species Species_new(const char *name,const char *genome) { Species result = malloc(sizeof(*result)); result->name = name; result->genome = genome; return result; }

Halloween 2002CS 201J Fall Memory Leaks for (i = 0; i < 10; i++) { int *p = malloc(sizeof(*p)); *p = i*i; printf(“%d squared is %d\n”,i,*p); } p i0 0

Halloween 2002CS 201J Fall Memory Leaks for (i = 0; i < 10; i++) { int *p = malloc(sizeof(*p)); *p = i*i; printf(“%d squared is %d\n”,i,*p); } p i1 0 1

Halloween 2002CS 201J Fall Memory Leaks for (i = 0; i < 10; i++) { int *p = malloc(sizeof(*p)); *p = i*i; printf(“%d squared is %d\n”,i,*p); } p i

Halloween 2002CS 201J Fall Detecting Memory Leaks for (i = 0; i < 10; i++) { int *p = malloc(sizeof(*p)); *p = i*i; printf(“%d squared is %d\n”,i,*p); } > splint leak.c Splint leak.c:11:6 Fresh storage p not released before scope exit A memory leak has been detected. Storage allocated locally is not released before the last reference to it is lost.

Halloween 2002CS 201J Fall free Java’s garbage collector automatically reclaims memory C has no garbage collector We must release memory explicitly using the free function

Halloween 2002CS 201J Fall Releasing Memory for (i = 0; i < 10; i++) { int *p = malloc(sizeof(*p)); *p = i*i; printf(“%d squared is %d\n”,i,*p); free(p); } p i9 81

Halloween 2002CS 201J Fall Releasing Memory Too Soon int f() { int *i = malloc(sizeof(*i)); *i = 42; free(i); printf(“i is %d\n”,*i); } The result is undefined!

Halloween 2002CS 201J Fall Avoiding Memory Leaks Whenever we allocate memory, there is a responsibility to release it We can specify what part of the code has this responsibility by using annotations. Code that uses an pointer must free the storage, or pass the responsibility somewhere else If an pointer is lost of goes out of scope, Splint warns of a possible memory leak.

Halloween 2002CS 201J Fall Why does Splint detect the error? for (i = 0; i < 10; i++) { int *p = malloc(sizeof(*p)); *p = i*i; printf(“%d squared is %d\n”,i,*p); } > splint leak.c Splint leak.c:11:6 Fresh storage p not released before scope exit A memory leak has been detected. Storage allocated locally is not released before the last reference to it is lost.

Halloween 2002CS 201J Fall Annotating Functions We can annotate functions to indicate how they delegate the responsibility to release memory: void * malloc(size_t bytes); void free(void * ptr); With these annotations, Splint knows: –Any call to malloc might return NULL –The caller of malloc is responsible for releasing the allocated memory.

Halloween 2002CS 201J Fall Annotating Functions We can annotate functions to indicate how they delegate the responsibility to release memory: void * malloc(size_t bytes); void void * ptr); With these annotations, Splint knows: –Any call to malloc might return NULL –The caller of malloc is responsible for releasing the allocated memory. –free will take responsibility for releasing an pointer.

Halloween 2002CS 201J Fall Annotating Constructors Species Species_new(const char *name, const char *genome) { Species s = malloc(sizeof(*s)); s->name = name; s->genome = genome; return s; }

Halloween 2002CS 201J Fall Annotating Constructors Species Species_new(const char *name, const char *genome) { Species s = malloc(sizeof(*s)); s->name = name; s->genome = genome; return s; }

Halloween 2002CS 201J Fall Annotating Constructors Species Species_new(const char *name, const char *genome) { Species s = malloc(sizeof(*s)); if (s == NULL) { fprintf(stderr,”Out of memory in Species_new.\n”); exit(EXIT_FAILURE); } s->name = name; s->genome = genome; return s; }

Halloween 2002CS 201J Fall Annotating Constructors Species const char *name, const char *genome) { Species s = malloc(sizeof(*s)); if (s == NULL) { fprintf(stderr,”Out of memory in Species_new.\n”); exit(EXIT_FAILURE); } s->name = name; s->genome = genome; return s; }

Halloween 2002CS 201J Fall Dependent and Owned Sometimes we need to have more than one pointer to the same object However, we want to be able to check that the object is released –Why can’t we use in this situation? references indicate an obligation to release the memory before the reference is lost references refer to objects that are by some other pointer

Halloween 2002CS 201J Fall Use of Dependent SpeciesSet holds references to Species objects We might want to put a single Species object into more than one SpeciesSet Therefore, SpeciesSet cannot take responsibility for releasing the Species object Some other reference must take responsibility for releasing the Species object void SpeciesSet_insert(SpeciesSet set, Species species);

Halloween 2002CS 201J Fall PS6: Phylogeny Revisited We have rewritten the Phylogeny program from Problem Set 4 in C The C version of the program has several errors: –Null pointer dereferences –Memory leaks –Abstraction violations Your job is to use Splint annotations to find and fix them

Halloween 2002CS 201J Fall Charge The C compiler does not check for null pointer dereferences or memory leaks Splint can catch many of these errors if the program is annotated correctly PS5: Due Today PS6: Use C and Splint (Phylogeny Revisited)