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.

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.
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.
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.
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.
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
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.
Introduction of Memory Allocation. Memory Allocation There are two types of memory allocations possible in c. Compile-time or Static allocation Run-time.
Engineering Problem Solving with C Fundamental Concepts Chapter 6 Pointers.
Kernighan/Ritchie: Kelley/Pohl:
Memory Allocation. Memory A memory or store is required in a computer to store programs (or information or data). Data used by the variables in a program.
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:
Dynamic memory allocation. The process of allocating memory at run time is known as dynamic memory allocation. C have four library functions for allocating.
Programming III SPRING 2015 School of Computer and Information Sciences Francisco R. Ortega, Ph.D. McKnight Fellow and GAANN Fellow LECTURE #5 More about.
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’;
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
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.
Lecture 2 Pointers Pointers with Arrays Dynamic Memory Allocation.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
Pointers Applications
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
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
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
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.
David Notkin Autumn 2009 CSE303 Lecture 12 October 24, 2009: Space Needle.
Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
CS 161 Introduction to Programming and Problem Solving Chapter 19 Single-Dimensional Arrays Herbert G. Mayer, PSU Status 10/8/2014 Initial content copied.
ECE 103 Engineering Programming Chapter 36 C Storage Classes Herbert G. Mayer, PSU CS Status 8/4/2014 Initial content copied verbatim from ECE 103 material.
ECE Application Programming
Introduction to Computer Organization & Systems Topics: C arrays C pointers COMP Spring 2014 C Part IV.
+ 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.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
ECE 103 Engineering Programming Chapter 23 Multi-Dimensional Arrays Herbert G. Mayer, PSU CS Status 6/24/2014 Initial content copied verbatim from ECE.
ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory. Dynamic vs Static Allocation Dynamic  On the heap  Amount of memory chosen at runtime  Can change allocated.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
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.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
CSE 220 – C Programming malloc, calloc, realloc.
Dynamic Allocation in C
Stack and Heap Memory Stack resident variables include:
Introduction to Programming
CSCI206 - Computer Organization & Programming
CSC215 Lecture Memory Management.
CS111 Computer Programming
EECE.2160 ECE Application Programming
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
Dynamic Memory A whole heap of fun….
EECE.2160 ECE Application Programming
Dynamic Memory A whole heap of fun….
C Programming Lecture-8 Pointers and Memory Management
ECE 103 Engineering Programming Chapter 38 C Pointers, Part 2
Dynamic Memory – A Review
EECE.2160 ECE Application Programming
Module 13 Dynamic Memory.
Presentation transcript:

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 material developed by Professor Phillip PSU ECE

Syllabus Memory Allocation Functions Creating a 1-D Array at Runtime Creating a 2-D Array at Runtime calloc, malloc, free Dangers

2 Memory Allocation Functions The size of arrays must be known at compile-time (C90 limitation only; C99 supports VLAs). A C program can also make a request at runtime for a memory block of arbitrary size. If the memory block is no longer needed, the system can be told to release the memory. To use C’s memory allocation functions, add #include to the source file.

3 calloc void * calloc (size_t N, size_t bsize); Allocates a block of memory from the heap at runtime to use for data storage.  Block can contain N items, each of size bsize.  Block is initialized to zero.  If successful, returns a pointer to the allocated memory.  If unsuccessful, returns the NULL value.  Storage persists until explicitly freed or the program terminates. Example: Create a block of storage for 512 integers at runtime. int *p; p = (int *) calloc(512, sizeof(int));

4 malloc void * malloc (size_t bsize); Allocates a block of memory from the heap at runtime to use for data storage.  Block is of size bsize.  Block is not initialized to zero (i.e., indeterminate values).  If successful, returns a pointer to the allocated memory.  If unsuccessful, returns the NULL value.  Storage persists until explicitly freed or the program terminates. Example: Create a 1024 character memory block at runtime. char *q; q = (char *) malloc(1024 * sizeof(char));

5 realloc void * realloc (void *p, size_t bsize); Changes the size of a previously allocated memory block.  p is a pointer to the existing block.  bsize is the desired new size.  If successful, returns a pointer to the resized block.  If unsuccessful, returns the NULL value. Example: Suppose p points to a 1024 char block created by malloc. Change the block’s size to p_new = (char *) realloc(p, 2048*sizeof(char));

6 free void * free (void *p); Releases memory that has been previously allocated by calloc, malloc, or realloc back to the heap.  p is a pointer to the existing block.  If p is NULL, then free does nothing. Example: Suppose p points to a dynamically allocated memory block. The storage is no longer needed, so free up the memory. free(p);

7 Potential Dangers … Dynamically allocated memory exists until it is released by free, or until the program terminates. If a pointer “loses track” of a memory block, and there are no other pointers still tracking that block, then the block becomes inaccessible. Inaccessible blocks still continue to use memory for as long as the program is running (memory leak).

8 mem… void * memset (void *ptr, int value, size_t num); Sets first num bytes of the memory block pointed by ptr to the specified value. void * memcpy (void *dst, const void *src, size_t num); Copies the values of num bytes from the location pointed by src to the memory block pointed by dst. No overlap is allowed. Returns dst. void * memmove (void *dst, const void *src, size_t num); Copies the values of num bytes from the location pointed by src to the memory block pointed by dst. Overlap is allowed. Returns dst. int memcmp (const void *ptr1, const void *ptr2, size_t num); Compares the first num bytes of the memory block pointed by ptr1 to the first num bytes pointed by ptr2. Returns zero if equal, or non-zero otherwise. void * memchr (const void *ptr, int value, size_t num); Searches within the first num bytes of the memory block pointed by ptr for the first occurrence of value. If found, returns pointer to location, or NULL otherwise.

9 Creating a 1-D Array at Runtime When declaring a normal array variable, the size of the array must be specified at compile-time (C90). Using dynamic memory allocation, an array can be created whose size is determined at runtime. The size of the desired block must be passed to either calloc or malloc. The sizeof() operator can determine the block size (in bytes) of a given datatype.

10 The pointer returned by calloc or malloc must be cast to the correct datatype. The pointer should always be tested for NULL! The allocated array can be accessed using array notation. A memory block should be freed when it is no longer needed.

11 Example: Create a 1-D array at runtime that holds up to 10 elements of datatype float. float *A; A = (float *) calloc(10, sizeof(float)); Pointer to the allocated memory block that will hold the 1-D array values. Desired 1-D array size Desired datatype Calculates size of datatype (in bytes) Casts the pointer returned by calloc to the correct datatype

12 Example: #include int main (void) { float *A;/* Pointer to 1-D array */ int R;/* Size of the array */ int i;/* Index */ printf("Enter size of the array: "); scanf("%d", &R); /* Create the array at runtime */ if ((A = (float *) calloc(R, sizeof(float))) == NULL) { printf("Error: Could not allocate memory block.\n"); exit(0); } /* Can now access using array notation */ for (i = 0; i < R; i++) A[i] = i; free(A);/* Free up the block */ return 0; }

13 Suppose the entered array size is R = 5 and the system uses 64 bit pointers and 32 bit float values. Assume that calloc returns 2000 as the start address of the allocated memory block. IndexAddressContents A →A →

14 Creating a 2-D Array at Runtime Creating a 1-D array using runtime memory allocation requires a single level of indirection (e.g., double * ). To create a 2-D array, two levels of indirection are required (e.g., double ** ). In other words, a pointer to a pointer is required.

15 The 2-D array is created in two phases:  The rows are created first. The return value is a pointer to a pointer.  For each row, columns are created. The return value in each case is a pointer. The pointers should always be tested for NULL! The block is released in reverse order, i.e., the columns are freed first and then the rows.

16 Example: Create a 2-D array (size: 5 rows by 3 columns) at runtime that holds elements of type float. float **A; /* Create array of pointers to the rows */ A = (float **) calloc(5, sizeof(float *)); /* Create the rows */ for (i = 0; i < 5; i++) A[i] = (float *) calloc(3, sizeof(float)); Pointer to the allocated row block that contains pointers to the column blocks

17 Example: #include int main (void) { float **A;/* Pointer to 2-D array */ int R = 5, C = 3;/* Row and column sizes of the array */ int i, j;/* Row and column indices */ /* Create the rows of the 2-D array */ if ((A = (float **) calloc(R, sizeof(float *))) == NULL) { printf("Error: Cannot allocate memory block.\n"); exit(0); } /* For each row, create the columns */ for (i = 0; i < R; i++) if ((A[i] = (float *) calloc(C, sizeof(float))) == NULL) { printf("Error: Cannot allocate memory block.\n"); exit(0); } /* Can now access using array notation */ for (i = 0; i < R; i++) for (j = 0; j < C; j++) A[i][j] = i+j; for (i = 0; i < R; i++) free(A[i]);/* Free up the columns a row at a time */ free(A); /* Free up the rows */ return 0; }

18 Suppose that R = 5, C = 3 and the system uses 64 bit pointers and 32 bit float values. Assume calloc returns 2000 as the start address of the row block. Suppose that when creating columns, calloc returned 3000, 3012, 3024, 4000, and 4012 for the start addresses of the column blocks. Note: The non-contiguous allocation may be inefficient. Some prefer using a 1-D allocated block and manually calculating 2-D offsets. Row IndexAddressContents A →A → Column index Address

19 VLA vs. Dynamic memory allocation What are some pros and cons of using C99’s variable- length arrays versus dynamic memory allocation? + VLAs are easy to define + No pointers to create + Automated memory management (no need to free) − VLAs are stored on the stack → Stack size is limited. Large VLA may overrun space. − Not portable to all compilers C99