Dynamic Memory Allocation (and Multi-Dimensional Arrays)

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

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)
User-Level Memory Management in Linux Programming
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.
Strings, Arrays, and Pointers CS-2303, C-Term Strings, Arrays, and Pointers CS-2303 System Programming Concepts (Slides include materials from The.
Digression on Stack and Heaps CS-502 (EMC) Fall A Short Digression on Stacks and Heaps CS-502, Operating Systems Fall 2009 (EMC) (Slides include.
Strings, Arrays, and Pointers CS-2301 D-term Strings, Arrays, and Pointers CS-2301 System Programming C-term 2009 (Slides include materials from.
Arrays in CCS-2301 B-term Arrays in C (with a brief Introduction to Pointers) CS-2301, System Programming for Non-majors (Slides include materials.
1 Chapter 9 Arrays and Pointers. 2  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
Stacks and HeapsCS-502 Fall A Short Digression Stacks and Heaps CS-502, Operating Systems Fall 2007 (Slides include materials from Operating System.
Pointers Applications
Strings, Arrays, and Pointers CS-2301, B-Term Strings, Arrays, and Pointers CS-2301, System Programming for Non-Majors (Slides include materials.
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.
Lecture 13 Static vs Dynamic Memory Allocation
Stack and Heap Memory Stack resident variables include:
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
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
ECE Application Programming Instructors: Dr. Michael Geiger & Nasibeh Nasiri Fall 2015 Lecture 31: Structures (cont.) Dynamic memory allocation.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
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.
CSE 220 – C Programming malloc, calloc, realloc.
Object Lifetime and Pointers
Dynamic Storage Allocation
Stack and Heap Memory Stack resident variables include:
Computer Organization and Design Pointers, Arrays and Strings in C
Day 03 Introduction to C.
Strings, Arrays, and Pointers
Day 03 Introduction to C.
Checking Memory Management
Lecture 6 C++ Programming
Advanced Programming Behnam Hatami Fall 2017.
Dynamic Memory Allocation
Programming and Data Structures
CSC215 Lecture Memory Management.
Dynamic Memory Allocation
CS111 Computer Programming
Memory Allocation CS 217.
EECE.2160 ECE Application Programming
Classes, Constructors, etc., in C++
Structures, Unions, and Typedefs
Arrays and Pointers in C & C++
Dynamic Memory A whole heap of fun….
Linked Lists in C and C++
Symbolic Constants in C
Scope Rules and Storage Types
Strings in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan.
CS111 Computer Programming
EENG212 – Algorithms & Data Structures Fall 07/08 – Lecture Notes # 5b
Pointers and Arrays Beyond Chapter 16
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
Dynamic Memory A whole heap of fun….
C Programming Lecture-8 Pointers and Memory Management
Chapter 10-1: Dynamic Memory Allocation
A Deeper Look at Classes
Dynamic Memory – A Review
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
Module 13 Dynamic Memory.
Presentation transcript:

Dynamic Memory Allocation (and Multi-Dimensional Arrays) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan and Ritchie, Absolute C++, by Walter Savitch, The C++ Programming Language, Special Edition, by Bjarne Stroustrup, and from C: How to Program, 5th and 6th editions, by Deitel and Deitel) CS-2303, A-Term 2012 Dynamic Memory Allocation

Dynamic Memory Allocation Problem What do you do if:– … the size of an array is not known until run time? OR … a function must return an array that it creates? How can we manipulate variable-length arrays and pass them around our programs? Answer:– Use dynamically allocated storage in The Heap! CS-2303, A-Term 2012 Dynamic Memory Allocation

Dynamic Memory Allocation Definition — The Heap A region of memory provided by most operating systems for allocating storage not in Last in, First out discipline I.e., not a stack Must be explicitly allocated and released May be accessed only with pointers Remember, an array is equivalent to a pointer Many hazards to the C programmer CS-2303, A-Term 2012 Dynamic Memory Allocation

Dynamic Data Allocation 0x00000000 0xFFFFFFFF address space program code (text) global and static data heap (dynamically allocated) stack PC SP This is The Heap CS-2303, A-Term 2012 Arrays and Pointers

Allocating Memory in The Heap See <stdlib.h> void *malloc(size_t size); void free(void *ptr); void *calloc(size_t nmemb, size_t size); void *realloc(void *ptr, size_t size); malloc() — allocates size bytes of memory from the heap and returns a pointer to it. NULL pointer if allocation fails for any reason free() — returns the chunk of memory pointed to by ptr back to the heap Must have been allocated by malloc() or calloc() free() knows size of chunk allocated by malloc() or calloc() Segmentation fault and/or big-time error if bad pointer CS-2303, A-Term 2012 Dynamic Memory Allocation

Dynamic Memory Allocation Notes calloc() is just a variant of malloc() malloc() is analogous to new in C++ and Java new in C++ actually calls malloc() free() is analogous to delete in C++ delete in C++ actually calls free() Java does not have delete — uses garbage collection to recover memory no longer in use CS-2303, A-Term 2012 Dynamic Memory Allocation

Example usage of malloc() and free() #include <stdlib.h> int PlayGame(int board[], int arraySize); int main(){ int s, t; int A[]; s = …; /* determine size of array from input */ A = malloc(s * sizeof(int)); …; t = PlayGame(A, s); … free(A); return t; } CS-2303, A-Term 2012 Dynamic Memory Allocation

Alternate version of malloc() and free() #include <stdlib.h> int PlayGame(int *board, int arraySize); int main(){ int s, t; int *A; s = …; /* determine size of array from input */ A = malloc(s * sizeof(int)); …; t = PlayGame(A, s); … free(A); return t; } CS-2303, A-Term 2012 Dynamic Memory Allocation

Dynamic Memory Allocation Generalization malloc() and free() are used … whenever you need a dynamically sized array whenever you need an array that does not follow last in, first out rule of The Stack Valid in all versions of C See p. 167 of K&R (§7.8.5) CS-2303, A-Term 2012 Dynamic Memory Allocation

Dynamic Memory Allocation malloc vs. calloc void *malloc(size_t #ofBytes) Takes number of bytes as argument Aligned to largest basic data type of machine Usually long int Does not initialize memory Returns pointer to void void *calloc(size_t #ofItems, size_t sizeOfItem) Takes number of # of items and size as argument Initializes memory to zeros; returns pointer to void calloc(n, itemSize)  malloc(n * itemSize) Plus initialization to zero CS-2303, A-Term 2012 Dynamic Memory Allocation

Dynamic Memory Allocation realloc() void *realloc(void *p, size_t newSize) Changes the size of a malloc’ed piece of memory by allocating new area (or changing size of old area) May increase or decrease size Data copied from old area to new area If larger, extra space is uninitialized free(p) – i.e., frees old area (if new area different from old) Returns pointer to void of new area See p. 252 of K&R Rarely used in C programming! CS-2303, A-Term 2012 Dynamic Memory Allocation

Definition – Memory Leak The steady loss of available memory in Heap due to program forgetting to free everything that was malloc’ed. Bug-a-boo of most large C and C++ programs If you overwrite or lose the value of a pointer to a piece of malloc’ed memory, there is no way to find it again! Automatically creating a memory leak Killing the program frees all memory! CS-2303, A-Term 2012 Dynamic Memory Allocation

Dynamic Memory Allocation Questions? CS-2303, A-Term 2012 Dynamic Memory Allocation

Multi-Dimensional Arrays int D[10][20] A one-dimensional array with 10 elements, each of which is an array with 20 elements I.e., int D[10][20] /*[row][col]*/ Last subscript varies the fastest I.e., elements of last subscript are stored contiguously in memory Also, three or more dimensions CS-2303, A-Term 2012 Dynamic Memory Allocation

Limitations of Multi-Dimensional Arrays C supports only fixed size multi-dimensional arrays Rows stored contiguously in memory  Compiler must know how many elements in a row Cannot pass an array to a function with open-ended number of elements per row void f(int A[][20], int nRows); /*okay*/ void f(int A[10][], int nCols); /*NOT okay */ void f(int A[][], int nRows, int nCols); /*also NOT okay */ Same for three or more dimensions! CS-2303, A-Term 2012 Dynamic Memory Allocation

Dynamic Two-Dimensional Arrays Array of pointers, one per row Each row is a one-dimensional array int x, y; /* x = #rows, y = #columns */ int **B = calloc(x, sizeof(int *)); for (i = 0; i < x; i++) B[i] = calloc(y, sizeof(int)); … /* to access element of row i, column j */ B[i][j] CS-2303, A-Term 2012 Dynamic Memory Allocation

Dynamic Memory Allocation Why does this work? int **B means the same as int *B[]; I.e., B is an array of pointers to int Therefore, B[i] is a pointer to int But if A is a pointer to int, then A[j] is the jth integer of the array A Substitute B[i] for A Therefore, B[i][j] is the jth integer of the ith row of B CS-2303, A-Term 2012 Dynamic Memory Allocation

Why does this work? (continued) When expression contains B[i][j], compiler generates code resembling int *temp = B + i; *(temp + j); … in order to access this element CS-2303, A-Term 2012 Dynamic Memory Allocation

Dynamic Memory Allocation Alternative Method int x, y; /* x = #rows, y = #columns */ int **B = calloc(x, sizeof(int *)); int elements[] = calloc(x*y, sizeof(int)); for (i = 0; i < x; i++) B[i] = &elements[i*y]; … /* to access element of row i, column j */ B[i][j] Why does this work? Exercise for the student! CS-2303, A-Term 2012 Dynamic Memory Allocation

Arrays as Function Parameters (again) void init(float A[], int arraySize); void init(float *A, int arraySize); Are identical function prototypes! Pointer is passed by value I.e. caller copies the value of a pointer of the appropriate type into the parameter A Called function can reference through that pointer to reach thing pointed to Most C programmers use pointer notation rather than array notation CS-2303, A-Term 2012 Dynamic Memory Allocation

Arrays as Function Parameters (continued) void init(float A[][], int rows, int columns); void init(float **A, int rows, int columns); Not Identical! Compiler complains that A[][] in header is incompletely specified Needs to know number of columns As if constant! Must use pointer notation in header or declaration In body of init, A[i][j] is still acceptable CS-2303, A-Term 2012 Dynamic Memory Allocation

Dynamic Memory Allocation Questions? CS-2303, A-Term 2012 Dynamic Memory Allocation