Week 9 Part 1 Kyle Dewey. Overview Dynamic allocation continued Heap versus stack Memory-related bugs Exam #2.

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

An introduction to pointers in c
Dynamic Memory Management
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
CSC 270 – Survey of Programming Languages C Lecture 6 – Pointers and Dynamic Arrays Modified from Dr. Siegfried.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
Lecture 10: Heap Management CS 540 GMU Spring 2009.
COMP 1402 Winter 2009 Tutorial #8 malloc / calloc / realloc.
Week 8 Kyle Dewey. Overview Exam #2 Multidimensional arrays Command line arguments void* Dynamic memory allocation Project #3 will be released tonight.
Programming in C Pointers and Arrays, malloc( ). 7/28/092 Dynamic memory In Java, objects are created on the heap using reference variables and the new.
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)
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.
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:
Discussion: Week 3/26. Structs: Used to hold associated data together Used to group together different types of variables under the same name struct Telephone{
Introduction to C Programming in Unix Environment - II Abed Asi Extended System Programming Laboratory (ESPL) CS BGU Fall 2014/2015 Some slides.
Week #10 Kyle Dewey. Overview Meeting times Typos Project #3 tidbits Exam Review.
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
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.
1 CS 201 Dynamic Data Structures Debzani Deb. 2 Run time memory layout When a program is loaded into memory, it is organized into four areas of memory.
Memory and C++ Pointers.  C++ objects and memory  C++ primitive types and memory  Note: “primitive types” = int, long, float, double, char, … January.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Pointers Applications
Week 9 Part 2 Kyle Dewey. Overview Announcement More with structs and memory Assertions Exam #2 Course review.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
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
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
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.
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.
CS 11 C++ track: lecture 4 Today: More on memory management the stack and the heap inline functions structs vs. classes.
Pointers OVERVIEW.
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.
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.
Dynamic Allocation Joe Meehean. Dynamic Allocation Memory for local objects is automatically created and reclaimed memory is created for it at beginning.
Week 2. Functions: int max3(int num1, int num2, int num3) {int result; result = max(max(num1,num2),num3); return result; } //max3.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Week 7 Part I Kyle Dewey. Overview Code from last time Array initialization Pointers vs. arrays Structs typedef Bubble sort (if time)
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.
Sudeshna Sarkar, CSE, IIT Kharagpur1 Structure and list processing Lecture
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
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:
Dynamic Allocation Review Structure and list processing
ENEE150 Discussion 07 Section 0101 Adam Wang.
Checking Memory Management
CSC215 Lecture Memory Management.
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Presentation transcript:

Week 9 Part 1 Kyle Dewey

Overview Dynamic allocation continued Heap versus stack Memory-related bugs Exam #2

Dynamic Allocation

Recall... Dynamic memory allocation allows us to request memory on the fly A way to use only what you need // size_t is an integral defined // elsewhere void* malloc( size_t numBytes ); void* calloc( size_t num, size_t size ); void* realloc( void* ptr, size_t size );

Recall... Requesting some unknown number of integers at runtime int numToAllocate; scanf( “%i”, &numToAllocate ); int* nums = malloc(sizeof( int ) * numToAllocate); int nums2[ numToAllocate ]; // ERROR

Multidimensional Arrays Need two separate allocations: Array of columns Each column individually

Example Function that makes a matrix with a given number of rows and columns, all initialized to 0 int** makeMatrix( int rows, int cols ){ int** retval = calloc(rows, sizeof(int*)); int row; for( row = 0; row < rows; row++ ) { retval[ row ] = calloc(cols, sizeof(int)); } return retval; }

Question What differs here? int** makeMatrix( int rows, int cols ){ int** retval = calloc(rows, sizeof(int*)); int* temp = calloc(cols, sizeof(int)); int row; for( row = 0; row < rows; row++ ) { retval[ row ] = temp; } return retval; }

With Structs Works the same way struct Foo {int x; int y;}; int main() { struct Foo* f = malloc( sizeof( struct Foo ) ); f->x = 10; f->y = f->x; return 0; }

With Structs Works the same way struct Foo {int x; int y;}; int main() { int x; struct Foo** fs = calloc( NUM_STRUCTS, sizeof( struct Foo* ) ); for(x = 0; x < NUM_STRUCTS; x++ ){ fs[ x ] = malloc( sizeof( struct Foo ) ); } return 0; }

Example We want to calculate the sample standard deviation of some input numbers This formula is below:

Problems We need the average in order to calculate it, so we need to keep the numbers around Can’t simply calculate as we go Don’t know how many numbers we need to read in Solution: Dynamic memory allocation!

stddev.c

Heap vs. Stack

Recall... Say we have multiple function calls int foo() { int x = 7; return x * 2; } int bar() { int y = 13; return y + foo(); } int baz() { int z = 24; return z * 3; } int main() { printf( “%i”, bar() ); return 0; }

Recall... How is this allocated in memory? int foo() { int x = 7; return x * 2; } int bar() { int y = 13; return y + foo(); } int baz() { int z = 24; return z * 3; } int main() { printf( “%i”, bar() ); return 0; }

One Possibility int foo() { int x = 7; return x * 2; } int bar() { int y = 13; return y + foo(); } int baz() { int z = 24; return z * 3; } x y z Address 0 1 2

Pros Simple Fast x y z Address 0 1 2

Cons Wasteful ( z is allocated but is unused in this code) Does not generally allow for recursion int fact( int n ) { if ( n == 0 ) { return 1; } else { return n * fact(n-1); } n Address 0

Another Possibility Use a stack As we call functions and declare variables, they get added to the stack As function calls end and variables are no longer alive, they get removed from the stack Do everything relative to the top of the stack

Stack int foo() { int x = 7; return x * 2; } int bar() { int y = 13; return y + foo(); } int baz() { int z = 24; return z * 3; } int main() { printf( “%i”, bar() ); return 0; } Address

Stack int foo() { int x = 7; return x * 2; } int bar() { int y = 13; return y + foo(); } int baz() { int z = 24; return z * 3; } int main() { printf( “%i”, bar() ); return 0; } Address

Stack int foo() { int x = 7; return x * 2; } int bar() { int y = 13; return y + foo(); } int baz() { int z = 24; return z * 3; } int main() { printf( “%i”, bar() ); return 0; } Address

Stack int foo() { int x = 7; return x * 2; } int bar() { int y = 13; return y + foo(); } int baz() { int z = 24; return z * 3; } int main() { printf( “%i”, bar() ); return 0; } Address y TOS

Stack int foo() { int x = 7; return x * 2; } int bar() { int y = 13; return y + foo(); } int baz() { int z = 24; return z * 3; } int main() { printf( “%i”, bar() ); return 0; } Address y TOS

Stack int foo() { int x = 7; return x * 2; } int bar() { int y = 13; return y + foo(); } int baz() { int z = 24; return z * 3; } int main() { printf( “%i”, bar() ); return 0; } Address y TOS

Stack int foo() { int x = 7; return x * 2; } int bar() { int y = 13; return y + foo(); } int baz() { int z = 24; return z * 3; } int main() { printf( “%i”, bar() ); return 0; } Address y TOS - 1 x TOS

Stack int foo() { int x = 7; return x * 2; } int bar() { int y = 13; return y + foo(); } int baz() { int z = 24; return z * 3; } int main() { printf( “%i”, bar() ); return 0; } Address y TOS - 1 x TOS

Stack int foo() { int x = 7; return x * 2; } int bar() { int y = 13; return y + foo(); } int baz() { int z = 24; return z * 3; } int main() { printf( “%i”, bar() ); return 0; } Address y TOS

Stack int foo() { int x = 7; return x * 2; } int bar() { int y = 13; return y + foo(); } int baz() { int z = 24; return z * 3; } int main() { printf( “%i”, bar() ); return 0; } Address

Notice The function baz was never called, and the variable z was thusly never put on the stack At all points, only exact as much memory as was needed was used

Recursion Since stacks grow dynamically and allocate on the fly, we can have recursion int fact( int n ) { if ( n == 0 ) { return 1; } else { return n * fact(n-1); } int main() { fact( 5 ); return 0; }

Recursion int fact( int n ) { if ( n == 0 ) { return 1; } else { return n * fact(n-1); } int main() { fact( 5 ); return 0; } fact(5) n: 5 TOS

Recursion int fact( int n ) { if ( n == 0 ) { return 1; } else { return n * fact(n-1); } int main() { fact( 5 ); return 0; } fact(5) n: 5 fact(4) n: 4 TOS

Recursion int fact( int n ) { if ( n == 0 ) { return 1; } else { return n * fact(n-1); } int main() { fact( 5 ); return 0; } fact(5) n: 5 fact(4) n: 4 fact(3) n: 3 TOS

Recursion int fact( int n ) { if ( n == 0 ) { return 1; } else { return n * fact(n-1); } int main() { fact( 5 ); return 0; } fact(5) n: 5 fact(4) n: 4 fact(3) n: 3 fact(2) n: 2 TOS

Recursion int fact( int n ) { if ( n == 0 ) { return 1; } else { return n * fact(n-1); } int main() { fact( 5 ); return 0; } fact(5) n: 5 fact(4) n: 4 fact(3) n: 3 fact(2) n: 2 fact(1) n: 1 TOS

Recursion int fact( int n ) { if ( n == 0 ) { return 1; } else { return n * fact(n-1); } int main() { fact( 5 ); return 0; } fact(5) n: 5 fact(4) n: 4 fact(3) n: 3 fact(2) n: 2 fact(1) n: 1 fact(0) n: 0 TOS

Stack Pros/Cons Only memory that is required is allocated Can have recursion Slower (everything now relative to the top of the stack instead of absolute)

Question Is there anything odd with this code? int* doSomething() { int x; return &x; } int main() { int w; int* p = doSomething(); *p = 5; return 0; }

Question Continued int* doSomething() { int x; return &x; } int main() { int w; int* p = doSomething(); *p = 5; return 0; } w TOS

Question Continued int* doSomething() { int x; return &x; } int main() { int w; int* p = doSomething(); *p = 5; return 0; } w TOS

Question Continued int* doSomething() { int x; return &x; } int main() { int w; int* p = doSomething(); *p = 5; return 0; } w TOS

Question Continued int* doSomething() { int x; return &x; } int main() { int w; int* p = doSomething(); *p = 5; return 0; } x TOS w TOS - 1

Question Continued int* doSomething() { int x; return &x; } int main() { int w; int* p = doSomething(); *p = 5; return 0; } x TOS w TOS - 1

Question Continued int* doSomething() { int x; return &x; } int main() { int w; int* p = doSomething(); *p = 5; return 0; } w TOS

Question Continued int* doSomething() { int x; return &x; } int main() { int w; int* p = doSomething(); *p = 5; return 0; } w TOS Once TOS is updated, w ’s address is the same as x ’s address

In General Stack allocation is done automatically Pointers to places on the stack are ok, as long as you make sure the address will always be alive Pointers to the stack can be safely passed as function parameters, but not safely returned

Heap Dynamic memory allocation allocates from a section of memory known as the heap Completely manual allocation Allocate when you need it Deallocate when you don’t The computer assumes you know what you’re doing

Heap Allocation Reconsider the code from before: int* doSomething() { // int x; // return &x; return malloc( sizeof( int ) ); } int main() { int w; int* p = doSomething(); *p = 5; return 0; }

Heap Allocation This code is perfectly fine There is nothing that will be automatically reclaimed Can pass pointers any which way

Heap Allocation Bugs

Memory Leak Allocated memory is not freed after it is needed (wasted) Generally, no pointers exist to the portion allocated, and so it can never be reclaimed Why do we need a pointer? void makeLeak() { malloc( sizeof( int ) ); }

Dangling Pointer We keep a pointer to something that has been freed That memory can do just about anything after it is freed int* dangle() { int* p = malloc( sizeof( int ) ); free( p ); *p = 5; return p; }

Double Free We called free on something that was already freed void doubleFree() { int* p = malloc( sizeof( int ) ); free( p ); }

On Memory Bugs Determining when something can be freed is generally difficult Theoretically impossible to determine precisely in general Try to use stack allocation as much as possible

Exam #2

Statistics Average: 78 Min: 52 Max: 97 A’s: 8 B’s: 12 C’s: 15 D’s: 4 F’s: 2