CSE 374 Programming Concepts & Tools

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Lecture 10: Heap Management CS 540 GMU Spring 2009.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
Pointers A pointer is a reference to another variable (memory location) in a program –Used to change variables inside a function (reference parameters)
1 Objectives ❏ To understand the relationship between arrays and pointers ❏ To understand the design and concepts behind pointer arithmetic ❏ To write.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
1 Day 03 Introduction to C. 2 Memory layout and addresses r s int x = 5, y = 10; float f = 12.5, g = 9.8; char c = ‘r’, d = ‘s’;
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Stack and Heap Memory Stack resident variables include:
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
David Notkin Autumn 2009 CSE303 Lecture 12 October 24, 2009: Space Needle.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
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.
Object-Oriented Programming in C++
Dynamic Memory. We will follow different order from Course Book We will follow different order from Course Book First we will cover Sect The new.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
1 Homework / Exam Finishing K&R Chapter 5 today –Skipping sections for now –Not covering section 5.12 Starting K&R Chapter 6 next Continue HW5.
© 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.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 12 – C: structs, linked lists, and casts.
1 Dynamic Memory Allocation. 2 In everything we have done so far, our variables have been declared at compile time. In these slides, we will see how to.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 17 – Specifications, error checking & assert.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
CSE 220 – C Programming malloc, calloc, realloc.
Memory Management.
Dynamic Allocation in C
Object Lifetime and Pointers
Dynamic Storage Allocation
Memory allocation & parameter passing
Computer Organization and Design Pointers, Arrays and Strings in C
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
CSE 374 Programming Concepts & Tools
Pointers.
Day 03 Introduction to C.
Motivation and Overview
CSE 374 Programming Concepts & Tools
CSE 374 Programming Concepts & Tools
CSE 303 Concepts and Tools for Software Development
CSE 374 Programming Concepts & Tools
Programmazione I a.a. 2017/2018.
Day 03 Introduction to C.
Checking Memory Management
CSCI206 - Computer Organization & Programming
Lecture 6 C++ Programming
8 Pointers.
Pointers and Dynamic Variables
Dynamic Memory Allocation
Dynamically Allocated Memory
Memory Allocation CS 217.
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
Dynamic Memory A whole heap of fun….
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
EECE.2160 ECE Application Programming
TUTORIAL 7 CS 137 F18 October 30th.
Dynamic Memory A whole heap of fun….
Homework Continue with K&R Chapter 5 Skipping sections for now
Pointers, Dynamic Data, and Reference Types
CSE 303 Concepts and Tools for Software Development
SPL – PS3 C++ Classes.
SPL – PS2 C++ Memory Handling.
CSE 303 Concepts and Tools for Software Development
Presentation transcript:

CSE 374 Programming Concepts & Tools Hal Perkins Winter 2017 Lecture 10 – C: the heap and manual memory management UW CSE 374 Winter 2017

Administrivia Midterm exam Monday(!) Topics – everything up to hw4 (including gdb concepts) These slides (malloc) are for next hw and final Old exams on web now for review Review Q&A Sunday, 1 pm (LOW 101) HW4 reminders (Re-)read the specifications (assignment) carefully, particularly after you “think” you’re done(!) clint: pay attention to most everything. Questions about edge cases, odd warnings, etc.? Discussion board! Watch late days – several people have used up all but 1 already – and a couple of people are out(!) Gradebook entry gives number we think you have left UW CSE 374 Winter 2017

Pointer syntax A review (for completeness) Declare a variable to have a pointer type: T * x; or T* x; or T *x; or T*x; (where T is a type and x is a variable) An expression to dereference a pointer: *x (or more generally *e) where e is an expression C’s designers used the same character on purpose, but declarations (create variable) and expressions (compute a value) are totally different things UW CSE 374 Winter 2017

Heap allocation So far, all of our ints, pointers, and arrays, have been stack-allocated, which in C has two huge limitations: The space is reclaimed when the allocating function returns The space required must (normally) be a constant (only an issue for arrays) Heap-allocation has neither limitation Comparison: new T(...) in Java does all this: Allocate space for a T (exception if out-of-memory) Initialize the fields to null or 0 Call the user-written constructor function Return a reference (hey, a pointer!) to the new object And the reference has a specific type: T In C, these steps are almost all separated UW CSE 374 Winter 2017

malloc, part 1 malloc is “just” a library function: it takes a number, heap-allocates that many bytes and returns a pointer to the newly-allocated memory Returns NULL on failure Does not initialize the memory You must cast the result to the pointer type you want You do not know how much space different values need! Do not do things like malloc(17) ! UW CSE 374 Winter 2017

malloc, part 2 malloc is “always” used in a specific way: (T*)malloc(e * sizeof(T)) Returns a pointer to memory large enough to hold an array of length e with elements of type T It is still not initialized (use a loop)! Underused friend: calloc (takes e and sizeof(T) as separate arguments, initializes everything to 0) malloc returns an untyped pointer (void*); the cast (T*) tells C to treat it as a pointer to a block of type T If allocation fails (extremely rare, but can happen), returns NULL. Programs must always check. UW CSE 374 Winter 2017

Half the battle We can now allocate memory of any size and have it “live” forever For example, we can allocate an array and use it indefinitely Unfortunately, computers do not have infinite memory so “living forever” could be a problem Java solution: Conceptually objects live forever, but the system has a garbage collector that finds unreachable objects and reclaims their space C solution: You explicitly free an object’s space by passing a pointer to it to the library function free Freeing heap memory correctly is very hard in complex software and is the disadvantage of C-style heap-allocation UW CSE 374 Winter 2017

Everybody wants to be free(d once) int * p = (int*)malloc(sizeof(int)); p = NULL; /* LEAK! */ int * q = (int*)malloc(sizeof(int)); free(q); free(q); /* HYCSBWK */ int * r = (int*)malloc(sizeof(int)); free(r); int * s = (int*)malloc(sizeof(int)); *s = 19; *r = 17; /* HYCSBWK, but maybe *s==17 ?! */ Problems much worse with functions: f returns a pointer; (when) should f’s caller free the pointed-to object? (i.e., who owns the pointed-to space?) g takes two pointers and frees one pointed-to object. Can the other pointer be dereferenced? UW CSE 374 Winter 2017

The Rules For every run-time call to malloc there should be one run-time call to free If you “lose all pointers” to an object, you can’t ever call free (a leak)! If you “use an object after it’s freed” (or free it twice), you used a dangling pointer! Note: It’s possible but rare to use up too much memory without creating “leaks via no more pointers to an object” Interesting side-note: The standard-library must “remember” how big the object is (but it won’t tell you) We will explore this further… later …. UW CSE 374 Winter 2017

Valgrind Ideally there are no memory leaks, dangling pointers, or other bugs, but how do we check? valgrind program program-arguments Runs program with program-arguments Catches pointer errors during execution At end, prints summary of heap usage, including details of any memory leaks at termination Option --leak-check=full gives more details, use it But it really slows down execution But still a fantastic diagnostic, debugging tool Valgrind has other options/tools but memory check is the default and most commonly used UW CSE 374 Winter 2017

Processes and the heap Recall: a process (running program) has a single address space (code, static/global, heap, stack) When a program terminates the address space is released by the OS So any allocated memory is “reclaimed” since it no longer exists Good practices OK to rely on this if appropriate, but… Any data structure package that allocates storage should normally provide routines to free it so client code can release the space if the client wants to UW CSE 374 Winter 2017