CS2110 Dynamic Allocation Chapter 19 Section 19.4 This file is called Mike-Ch19.ppt.

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
COMP 1402 Winter 2009 Tutorial #8 malloc / calloc / realloc.
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.
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)
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Managing Memory DCT 1063 PROGRAMMING 2 Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
User-Level Memory Management in Linux Programming
Agenda  Review: pointer & array  Relationship between pointer & array  Dynamic memory allocation.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 6: Dynamic Memory Allocation (DMA)
CS1372: HELPING TO PUT THE COMPUTING IN ECE CS1372 Memory.
Kernighan/Ritchie: Kelley/Pohl:
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:
Programming III SPRING 2015 School of Computer and Information Sciences Francisco R. Ortega, Ph.D. McKnight Fellow and GAANN Fellow LECTURE #5 More about.
Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
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.
CS 61C L03 C Arrays (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #3: C Pointers & Arrays
Pointers Applications
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
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.
Stack and Heap Memory Stack resident variables include:
Week 9 Part 1 Kyle Dewey. Overview Dynamic allocation continued Heap versus stack Memory-related bugs Exam #2.
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.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.
ECE Application Programming
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 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.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Announcements Partial Credit Due Date for Assignment 2 now due on Sat, Feb 27 I always seem to be behind and get tons of daily. If you me and.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
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 220 – C Programming malloc, calloc, realloc.
Dynamic Allocation in C
Stack and Heap Memory Stack resident variables include:
Introduction to Programming
ENEE150 Discussion 07 Section 0101 Adam Wang.
CSCI206 - Computer Organization & Programming
Dynamic Memory Allocation
Dynamic Memory Allocation
CS157: Dynamic Memory Dynamic Memory 11/9/201804/25/06.
Clear1 and Clear2 clear1(int array[], int size) { int i; for (i = 0; i < size; i += 1) array[i] = 0; } clear2(int *array, int size) {
CSC215 Lecture Memory Management.
Dynamic Memory Allocation
Memory Allocation CS 217.
EECE.2160 ECE Application Programming
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
Dynamic Memory A whole heap of fun….
CS111 Computer Programming
Chien-Chung Shen CIS/UD
EENG212 – Algorithms & Data Structures Fall 07/08 – Lecture Notes # 5b
EECE.2160 ECE Application Programming
Dynamic Memory A whole heap of fun….
Dynamic Memory – A Review
EECE.2160 ECE Application Programming
SPL – PS2 C++ Memory Handling.
Module 13 Dynamic Memory.
Presentation transcript:

CS2110 Dynamic Allocation Chapter 19 Section 19.4 This file is called Mike-Ch19.ppt

CS2110 Outline We will learn how to allocate dynamic (that is, runtime-controllable) amounts of memory in C This will basically be making dynamically sized arrays

CS2110 Dynamic Allocation Used when space requirements are unknown at compile time. Most of the time the amount of space required is unknown at compile time. Example –Need space to allow user to enter some data –80 bytes? 132? 1? 256? 255? Three Friends –malloc –realloc –free

CS2110 Every time a C programmer uses malloc incorrectly, a kitten explodes Only your C skills can save me! Picture CC license

CS2110 Mike’s Kitten Saving Challenge I count 16 different common ways to screw up malloc in this lecture Use the paper I’ve given you, and write down every one you can find as we go I am absolutely not kidding when I tell you that a malloc bug can waste numerous programmer-weeks 0

CS2110 malloc int *ip; ip = malloc(10 * sizeof(int)); if(ip == NULL) { /* Handle Error! */ } Options for handling error –Abort –Ask again –Save user data –Ask for less –Free up something 1

CS2110 malloc int *ip; ip = malloc(10 * sizeof(int)); = if(ip = NULL) { /* Handle Error! */ } Note how incredibly bad it would be to use the assignment operator! The pointer would be set to NULL The error code would be skipped Some programmers use: NULL == ip 2

CS2110 malloc -- What happens? int foo(int n) { int *ip; ip = malloc(n * sizeof(int)); if(ip == NULL) { /* Handle Error! */ }... Stack Heap Data Code 40 bytes

CS2110 Anticipating Problems ip = malloc(10 * sizeof(int)); if(ip == NULL) What might go wrong? Be paranoid!

CS2110 Welcome to my nightmare! ip = malloc(10 * sizeof(int)); Code foolishly inserted here! if(ip == NULL) Be afraid. Be very afraid! 3

CS2110 Tricky but safe if((ip = malloc(10*sizeof(int))) == NULL) { /* Handle Error Here */ }

CS2110 Using the space int sample(int n) { int i; int *ip; if((ip = malloc(n*sizeof(int))) == NULL) { /* Handle Error Here */ } for(i = 0; i < n; i++) ip[i] = 0;...

CS2110 Flexibility #define MAX 10 int *ip; ip = malloc(MAX * sizeof(int)); What if we change the type of int *ip??? #define MAX 10 int *ip; ip = malloc(MAX * sizeof(*ip)); 4

CS2110 After some calls to malloc Stack Heap Non-constant data Constant data Code

CS2110 What does runtime track? Address Size Notice that no record is made of the name of any pointer

CS2110 What happens? int *ip; ip = malloc(...);. free(ip);

CS2110 Prototypes void *malloc(size_t n); void free(void *p); void *realloc(void *p, size_t n); voidWhat is this mysterious void pointer?

CS2110 void pointer Not originally in c Relatively recent addition Basically a “generic” pointer Intended for use in applications like free where the block of memory located at some address will be freed without any necessity of defining the type

CS2110 Powerful & Dangerous void *vp; char *cp; int *ip; ip = cp; /* illegal */ Instead ip = (int *)cp; Or vp = cp; /* Legal, powerful and */ ip = vp; /* dangerous!!! */ Why is this being done? 6

CS2110 Casting Usually casting is not required May be masking a problem int *ip; char *cp;... *cp = ‘x’; *ip = ??? *ip = 42; *cp = ??? ip cp

CS2110 Warnings badUsing void pointers as a crutch to get around casting is a “ bad ” thing! Malloc doesn’t care what you are doing with a block of memory it allocates to you. What you do with the memory is your responsibility badPassing in non-malloced values to free is a bad thing! Free does not change contents of block that was freed Free does not change pointer After a call to free it is possible to do anything to the freed memory that was possible before the call!!! badDefinitely a bad thing!!! 67

CS2110 Persistent Data I char *foo(void) { static char ca[10]; return ca; } Anyone calling this function now has access to this block. Could be dangerous. Why? Note that this approach is not dynamic

CS2110 Example char *strFromUnsigned(unsigned u) { /* this is the important part */ static char strDigits[] = “?????”; char *pch; pch = &strDigits[5]; /* you can trust us that this really will convert an unsigned to a string */ do *--pch = (u % 10) + '0'; while((u /= 10) > 0); return pch; }

CS2110 Problem in use strHighScore = strFromUnsigned(HighScore);. strThisScore = strFromUnsigned(ThisScore); 8

CS2110 Persistent Data II char *foo(void) { char ca[10]; return ca; } Since ca was allocated on stack during function call pointer returned is now pointing to who knows what Bad 9

CS2110 Persistent Data III char *foo(void) { char *ca = malloc(...); /* error checking but no free */ return ca; }

CS2110 Memory Leaks Memory leaks occur when the programmer loses track of memory allocated by malloc or other functions that call malloc void foo(void) { char *ca = malloc(...); /* no free */ return; } Bad 10

CS2110 Memory Leaks Obviously a program that runs for a fraction of a second and then terminates will not cause a problem if it leaks a few bytes of memory. However, for real world programs memory leaks are not acceptable. For the educational purposes of this class your programs will be required to leak no memory! Programs submitted with memory leaks may incur severe penalties.

CS2110 Memory Management Some functions that call malloc –calloc –strdup –regcmp –others... C doesn’t do automatic memory management for efficiency reasons –If you want to manage memory...do it yourself!

CS2110 Memory Management Ok? int *ip, *ip2; ip = malloc(...); ip2 = ip; free(ip); *ip2 = 42; 1.Yes 2.No 3.Maybe

CS2110 Memory Management Ok? int *ip, *ip2; ip = malloc(...); ip2 = ip; free(ip); *ip2 = 42; 1.Yes 2.No 3.Maybe 11

CS2110 More... int *ip, *ip2;/* Line 1 */ ip = malloc(...);/* Line 2 */ /* Error checking here */ ip2 = ip;/* Line 3 */ ip += 4;/* Line 4 */ free(ip);/* Line 5 */ free(ip2);/* Line 6 */ Problem line? 1312

CS2110 Realloc ptr = realloc(ptr, num_bytes); What it does (conceptually) –Find space for new allocation –Copy original data into new space –Free old space –Return pointer to new space

CS2110 Realloc ptr in-use Before After

CS2110 Realloc: What might happen ptr unused Before After

CS2110 Dynamic Allocation int *ip = malloc(...); malloc may allocate more space than requested Why? Efficiency Typically if you ask for 1 byte you will get 8. Given this line of code char *cp = malloc(1); Which is more likely –Program will probably keep this memory as is –Program will eventually realloc How much can you safely use?

CS2110 Safety Program should only use memory actually requested Big problem! Why? Program that oversteps bounds may work... Sometimes! Note... char *cp = malloc(1); ADDR SIZE cp 8 (maybe!) Now... realloc(cp,6); will return same pointer thus... 14

CS2110 Realloc May return same pointer passed to it without indicating any problem. Using memory beyond that which has been allocated may work Some of the time Normally it will work when tested by a student but will fail when tested by a TA (for a grade) Go figure Thus the “No Mercy” rule

CS2110 Realloc Realloc may return –same pointer –different pointer –NULL Is this a good idea? cp = realloc(cp, n); 1.Yes 2.No 3.Sometimes

CS2110 Realloc Is this a good idea? cp = realloc(cp, n); No! If realloc returns NULL cp is lost Memory Leak! 15

CS2110 How to do it void *tmp; if((tmp = realloc(cp,...)) == NULL) { /* realloc error */ } else { cp = tmp; free(tmp); } NO! 16

CS2110 Additional Information realloc(NULL, n)  malloc(n); realloc(cp, 0)  free(cp); These can be used to make realloc work in a single loop design to build a dynamic structure such as a linked list.

CS2110 Kitty Challenge Reprise