CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 10 – C: the heap and manual memory management.

Slides:



Advertisements
Similar presentations
Linked Lists CSE 2451 Matt Boggus. Dynamic memory reminder Allocate memory during run-time malloc() and calloc() – return a void pointer to memory or.
Advertisements

Dynamic memory allocation
Chapter 6 Data Types
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.
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
Pointers A pointer is a reference to another variable (memory location) in a program –Used to change variables inside a function (reference parameters)
Managing Memory DCT 1063 PROGRAMMING 2 Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
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.
1 Objectives ❏ To understand the relationship between arrays and pointers ❏ To understand the design and concepts behind pointer arithmetic ❏ To write.
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
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’;
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Pointers and Dynamic Variables. Objectives on completion of this topic, students should be able to: Correctly allocate data dynamically * Use the new.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Outline Midterm results Static variables Memory model
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.
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.
Week 9 Part 1 Kyle Dewey. Overview Dynamic allocation continued Heap versus stack Memory-related bugs Exam #2.
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++
Pointers in C++. 7a-2 Pointers "pointer" is a basic type like int or double value of a pointer variable contains the location, or address in memory, of.
Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 9.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
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.
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.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
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.
Announcements You will receive your scores back for Assignment 2 this week. You will have an opportunity to correct your code and resubmit it for partial.
CSE 333 – SECTION 2 Memory Management. Questions, Comments, Concerns Do you have any? Exercises going ok? Lectures make sense? Homework 1 – START EARLY!
CS 100Lecture 221 Announcements P5 due Thursday Final Exam: Tuesday August 10, 8AM - 10AM, Olin 155 Want references? Remember to drop off a picture and.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
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.
Dynamic Allocation in C
Object Lifetime and Pointers
CSE 374 Programming Concepts & Tools
CSE 374 Programming Concepts & Tools
CSE 374 Programming Concepts & Tools
Checking Memory Management
CSCI206 - Computer Organization & Programming
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.
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
CSE 303 Concepts and Tools for Software Development
SPL – PS2 C++ Memory Handling.
CSE 303 Concepts and Tools for Software Development
Presentation transcript:

CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 10 – C: the heap and manual memory management

Administrivia Midterm exam Monday(!) –Topics – everything up to hw4 (including gdb) These slides (malloc) are for next hw and final –Old exams on web now for review –Review Q&A Sunday. 1pm (SAV 264?) Remember to switch to standard time 2am Sun. HW4 reminders –(Re-)read the specifications (assignment) carefully –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 2

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 space) and expressions (compute a value) are totally different things 3

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 4

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) ! 5

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. 6

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 7

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? –g takes two pointers and frees one pointed-to object. Can the other pointer be dereferenced? 8

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 …. 9

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 provides 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 10

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 11