David Notkin Autumn 2009 CSE303 Lecture 12 October 24, 2009: Space Needle.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Carnegie Mellon 1 Dynamic Memory Allocation: Basic Concepts : Introduction to Computer Systems 17 th Lecture, Oct. 21, 2010 Instructors: Randy Bryant.
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.
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
Managing Memory DCT 1063 PROGRAMMING 2 Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
1 Memory Allocation Professor Jennifer Rexford COS 217.
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.
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:
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’;
David Notkin Autumn 2009 CSE303 Lecture 10 "If it weren't for C, we'd be writing programs in BASI, PASAL, and OBOL."
CSE 2501 Review Declaring a variable allocates space for the type of datum it is to store int x; // allocates space for an int int *px; // allocates space.
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.
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
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
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
CS50 SECTION: WEEK 4 Kenny Yu. Announcements  Problem Set 4 Walkthrough online  Problem Set 2 Feedback has been sent out  CORRECTION: Expect all future.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
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:
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Storage Management. The stack and the heap Dynamic storage allocation refers to allocating space for variables at run time Most modern languages support.
Week 9 Part 1 Kyle Dewey. Overview Dynamic allocation continued Heap versus stack Memory-related bugs Exam #2.
Programming in C Advanced Pointers. Pointers to Pointers Since a pointer is a variable type, a pointer may point to another pointer.Since a pointer is.
C Programming Lecture 10-1 : Array & Pointer. Character Array String A sequence of characters The last character should be ‘\0’ that indicates “the end.
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.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
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++
Dynamic Allocation Joe Meehean. Dynamic Allocation Memory for local objects is automatically created and reclaimed memory is created for it at beginning.
Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
ECE Application Programming
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
Topics memory alignment and structures typedef for struct names bitwise & for viewing bits malloc and free (dynamic storage in C) new and delete (dynamic.
Memory Management in Java Computer Science 3 Gerb Objective: Understand references to composite types in Java.
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.
Arrays, Strings, and Memory. Command Line Arguments #include int main(int argc, char *argv[]) { int i; printf("Arg# Contents\n"); for (i = 0; i < argc;
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
Dynamic Allocation in C
Stack and Heap Memory Stack resident variables include:
CSE 374 Programming Concepts & Tools
ENEE150 Discussion 07 Section 0101 Adam Wang.
Storage Management.
Dynamic Memory Allocation
Dynamic Memory Allocation
Memory Allocation CS 217.
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
CS111 Computer Programming
Dynamic Memory A whole heap of fun….
Dynamic Memory.
CSE 303 Lecture 10 C memory model; stack allocation
Dynamic Memory – A Review
Pointers, Dynamic Data, and Reference Types
CSE 303 Concepts and Tools for Software Development
Presentation transcript:

David Notkin Autumn 2009 CSE303 Lecture 12 October 24, 2009: Space Needle

Upcoming schedule CSE303 Au092 Today 10/23 Monday 10/26 Wednesday 10/28 Friday 10/30 Monday 11/2 Finish-up Wednesday Some specifics for HW3 Social implications Friday Memory managementMidterm review Midterm Swap Arrays as parameters and returns Arrays vs. pointers The heap Dynamic memory allocation (malloc, calloc, free) Memory leaks and corruption

CSE303 Au093 #include int main(int argc, char *argv[]) { int a,b; scanf("%d %d",&a,&b); printf("Before swap: a=%d b=%d\n",a,b); swap(a,b); printf("After return from swap: a=%d b=%d\n",a,b); swap2(&a,&b); printf("After return from swap2: a=%d b=%d\n",a,b); } swap(int x,int y) { int t; t = x; x = y; y = t; printf("Before return from swap: x=%d y=%d\n",x,y); } swap2(int *f,int *g) { int t; t = *f; *f = *g; *g = t; printf("Before return from swap2: f=%d g=%d\n",*f,*g); }

swap2 (after assignments) g f t 6 swap2 (before assignments) g f t ? swap (before assignments) y 5 x 6 t ? swap (after assignments) y 6 x 5 t 6

Arrays and pointers A pointer can point to an array element An array's name can be used as a pointer to its first element The [] notation treats a pointer like an array –pointer[i] is i elements' worth of bytes forward from pointer int a[5] = {10, 20, 30, 40, 50}; int* p1 = &a[3]; // a's 4 th element int* p2 = &a[0]; // a's 1 st element int* p3 = a; // a's 1 st element *p1 = 100; *p2 = 200; p1[1] = 300; p2[1] = 400; p3[2] = 500; Final array contents: {200, 400, 500, 100, 300}

“pointer[i] is i elements' worth of bytes” – what is an “elements’ worth”? int x; int a[5]; printf("int=%d,double=%d\n", sizeof(int), sizeof(double)); printf("x uses %d bytes\n", sizeof(x)); printf("a uses %d bytes\n", sizeof(a)); printf("a[0] uses %d bytes\n", sizeof(a[0])); int=4, double=8 x uses 4 bytes a uses 20 bytes a[0] uses 4 bytes sizeof(type) or sizeof(variable) returns memory size in bytes Arrays passed as parameters do not remember their size int a[5]; printf("a uses %d bytes\n", sizeof(a)); f(a); void f(int a[]) { printf("a uses %2d bytes in f\n", sizeof(a)); } a uses 20 bytes a uses 4 bytes in f CSE303 Au096

Arrays as parameters Array parameters are passed as pointers to the first element; the [] syntax on parameters is only a convenience – the two programs below are equivalent void f(int a[]); int main(void) { int a[5];... f(a); return 0; } void f(int a[]) {... } void f(int* a); int main(void) { int a[5];... f(&a[0]); return 0; } void f(int* a) {... }

Returning an array Stack-allocated variables disappear at the end of the function: this means an array cannot generally be safely returned from a method int main(void) { int nums[4] = {7, 4, 3, 5}; int nums2[4] = copy(nums, 4); // no return 0; } int[] copy(int a[], int size) { int i; int a2[size]; for (i = 0; i < size; i++) { a2[i] = a[i]; } return a2; // no }

Pointers (alone) don't help A dangling pointer points to an invalid memory location int main(void) { int nums[4] = {7, 4, 3, 5}; int* nums2 = copy(nums, 4); // nums2 dangling here... } int* copy(int a[], int size) { int i; int a2[size]; for (i = 0; i < size; i++) { a2[i] = a[i]; } return a2; }

Our conundrum We'd like to have C programs with data that are –Dynamic (size of array changes based on user input, etc.) –Long-lived (doesn't disappear after the function is over) –Bigger (the stack can't hold all that much data) Currently, our solutions include: –Declaring variables in main and passing as "output parameters" –Declaring global variables (do not want)

The heap The heap (or "free store") is a large pool of unused memory that you can use for dynamically allocating data It is allocated/deallocated explicitly, not (like the stack) on function calls/returns Many languages (e.g. Java) place all arrays/ objects on the heap // Java int[] a = new int[5]; Point p = new Point(8, 2);

malloc : allocating heap memory variable = (type*) malloc(size); malloc function allocates a heap memory block of a given size –returns a pointer to the first byte of that memory –can/should cast the returned pointer to the appropriate type –initially the memory contains garbage data –often used with sizeof to allocate memory for a given data type int* a = (int*) malloc(8 * sizeof(int)); a[0] = 10; a[1] = 20;...

calloc : allocate and zero variable = (type*) calloc(count, size); calloc function is like malloc, but it zeros out the memory –also takes two parameters, number of elements and size of each –preferred over malloc for avoiding bugs (but slightly slower) #include // int a[8] = {0}; <-- stack equivalent int* a = (int*) calloc(8, sizeof(int));

Returning a heap array To return an array, malloc it and return a pointer –Array will live on after the function returns int main(void) { int nums[4] = {7, 4, 3, 5}; int* nums2 = copy(nums, 4);... int* copy(int a[], int size) { int i; int* a2 = malloc(size * sizeof(int)); for (i = 0; i < size; i++) { a2[i] = a[i]; } return a2; }

NULL : an invalid memory location In C, NULL is a global constant whose value is 0 If you malloc/calloc but have no memory free, it returns NULL You can initialize a pointer to NULL if it has no meaningful value Dereferencing a null pointer will crash your program int* p = NULL; *p = 42; // segfault Exercise : Write a program that figures out how large the stack and heap are for a default C program.

Deallocating memory Heap memory stays allocated until the end of your program A garbage collector is a process that automatically reclaims memory no longer in use –Keeps track of which variables point to which memory, etc. –Used in Java and many other modern languages; not in C // Java public static int[] f() { int[] a = new int[1000]; int[] a2 = new int[1000]; return a2; } // no variables refer to a here; can be freed

Memory leaks A memory leak is a failure to release memory when no longer needed. –easy to do in C –can be a problem if your program will run for a long time –when your program exits, all of its memory is returned to the OS void f(void) { int* a = (int*) calloc(1000, sizeof(int));... } // oops; the memory for a is now lost

free : releases memory free(pointer); Releases the memory pointed to by the given pointer –precondition: pointer must refer to a heap- allocated memory block that has not already been freed –it is considered good practice to set a pointer to NULL after freeing int* a = (int*) calloc(8, sizeof(int));... free(a); a = NULL;

Memory corruption If the pointer passed to free doesn't point to a heap-allocated block, or if that block has already been freed, bad things happen –you're lucky if it crashes, rather than silently corrupting something int* a1 = (int*) calloc(1000, sizeof(int)); int a2[1000]; int* a3; int* a4 = NULL; free(a1); // ok free(a1); // bad (already freed) free(a2); // bad (not heap allocated) free(a3); // bad (not heap allocated) free(a4); // bad (not heap allocated)

Questions? CSE303 Au0920