ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 6: Dynamic Memory Allocation (DMA)

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.
Dynamic Memory Allocation
CSE 251 Dr. Charles B. Owen Programming in C1 Dynamic Memory Allocation Dynamic memory allocation – How to allocate memory for variables (esp. arrays/strings)
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.
1 Memory Allocation Professor Jennifer Rexford COS 217.
More Pointers Write a program that: –Calls a function to input an integer value –The above function calls another function that will double the input value.
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:
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Dynamic memory allocation. The process of allocating memory at run time is known as dynamic memory allocation. C have four library functions for allocating.
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.
Dynamic Memory Allocation in C++. Memory Segments in C++ Memory is divided in certain segments – Code Segment Stores application code – Data Segment Holds.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 5: Pointers.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 3: Functions.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 4: Arrays and Strings.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 8: Recursion.
Pointers Applications
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
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
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.
Lecture 13 Static vs Dynamic Memory Allocation
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,
Week 9 Part 1 Kyle Dewey. Overview Dynamic allocation continued Heap versus stack Memory-related bugs Exam #2.
Pointers OVERVIEW.
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.
Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
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.
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.
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.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
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.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
CSE 220 – C Programming malloc, calloc, realloc.
Stack and Heap Memory Stack resident variables include:
Day 03 Introduction to C.
CSCI206 - Computer Organization & Programming
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) {
Programming and Data Structures
CSC215 Lecture Memory Management.
Dynamic Memory Allocation
Dynamic Memory Allocation
Memory Allocation CS 217.
Dynamic Memory Allocation
Chien-Chung Shen CIS/UD
EENG212 – Algorithms & Data Structures Fall 07/08 – Lecture Notes # 5b
Chapter 10-1: Dynamic Memory Allocation
Module 13 Dynamic Memory.
Presentation transcript:

ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 6: Dynamic Memory Allocation (DMA)

ספטמבר 04Copyright Meir Kalech2 What is Dynamic Memory Allocation? The problem: Array definition: its size must be known at compilation time. The array, when used, may be either too small – not enough room for all the elements, or too big – so it ’ s a waste of memory. The solution: Use Dynamic Memory Allocation (DMA): create the array at run-time, after determining the required number of elements. Dynamic memory allocation enables the programmer to: Request exactly the required amount of memory. Release the allocated memory when it is no longer needed.

ספטמבר 04Copyright Meir Kalech3 malloc Function malloc function enables to allocate memory at run-time. Syntax: malloc(number of requested bytes); Example: int size; printf(“how many integers?”); scanf(“%d”, &size); malloc(size*sizeof(int)); Comment: All the allocation functions use the library.

ספטמבר 04Copyright Meir Kalech4 calloc Function calloc function enables to allocate memory at run time. The allocated memory is initialized (cleared) with zeros. Syntax: calloc(number of elements, size of each element); Example: int size; printf(“how many integers?”); scanf(“%d”, &size); calloc(size, sizeof(int)); FINE! But I can ’ t access the allocated memory!?

ספטמבר 04Copyright Meir Kalech5 Allocation malloc and calloc return the first address of the allocated memory. Upon failure, they return NULL (0). We can save the return value in a pointer, and access the memory by using the operator * or operator []. For instance: int size; int *pointer; printf(“how many integers?”); scanf(“%d”, &size); pointer = malloc(size*sizeof(int)); if(pointer != NULL) pointer[0] = 54; DON ’ T WORRY!!! Pointers will help you!

ספטמבר 04Copyright Meir Kalech6 Allocation pointer = malloc(size*sizeof(int)); Problem: What type does malloc return? int *, char *, float * ??? Answer: void * !!! void * may be changed to any pointer type by using casting. pointer = (int *) malloc(size*sizeof(int));

ספטמבר 04Copyright Meir Kalech7 Heap Where is the memory allocated? Reminder: we studied about the “ stack segment ” and “ data segment ”. Stack segment is dedicated to local variables. Allocated memory is not a local variable. Conclusion: dynamic memory is allocated in the data segment (heap). Data segment:Stack segment: 500 p: 100 ????? 500 int *p = (int *) malloc(5*sizeof(int));

ספטמבר 04Copyright Meir Kalech8 Comment BE CAREFUL: A pointer that points to allocated memory can be mistakenly assigned to another memory address. In this case, we might lose our connection to the previously allocated memory. Data segment:Stack segment: 500 p: 100 ????? 500 int *p = (int *) malloc(5*sizeof(int));

ספטמבר 04Copyright Meir Kalech9 Comment BE CAREFUL: A pointer that points to allocated memory can be mistakenly assigned to another memory address. In this case, we might lose our connection to the previously allocated memory. Data segment:Stack segment: 200 p: 100 ????? 500 ??? arr: 200 NOW NOT ACCESSIBLE!! int *p = (int *) malloc(5*sizeof(int)); int arr[3]; p = arr;

ספטמבר 04Copyright Meir Kalech10 Comment To avoid this problem, we can first save the address in another pointer: Data segment: Stack segment: 200 p: 100 ????? 500 ??? arr: 200 ACCESSIBLE through save 500 save: 300 int *save, *p = (int *) malloc(5*sizeof(int)); int arr[3]; save = p; p = arr;

ספטמבר 04Copyright Meir Kalech11 free Function Since dynamic memory is allocated in the data segment, it is not deleted when the end of a block is reached, but it ’ s the programmer responsibility to explicitly delete it. The free function gets the first address of an allocated memory, and frees it: Syntax: free(first_address);

ספטמבר 04Copyright Meir Kalech12 free Function Data segment: Stack segment: 500 p1: 100 ????? 500 int *p1, *p2; p1 = (int *) malloc(5*sizeof(int)); p2 = (int *) malloc(3*sizeof(int)); free(p2); free(p1); 300 p2: ???

ספטמבר 04Copyright Meir Kalech13 free Function Data segment: Stack segment: 500 p1: 100 int *p1, *p2; p1 = (int *) malloc(5*sizeof(int)); p2 = (int *) malloc(3*sizeof(int)); free(p2); free(p1); 300 p2: 200

ספטמבר 04Copyright Meir Kalech14 free Function Data segment: Stack segment: 500 p1: p2: 200 BE CAREFUL!!! Avoid freeing memory that is already freed (execution error) int *p1, *p2; p1 = (int *) malloc(5*sizeof(int)); p2 = (int *) malloc(3*sizeof(int)); free(p2); free(p1);

ספטמבר 04Copyright Meir Kalech15 free Function Data segment: Stack segment: 0 p1: p2: 200 int *p1, *p2 p1 = (int *) malloc(5*sizeof(int)); p2 = (int *) malloc(3*sizeof(int)); free(p2); free(p1); p1=NULL; free(p1); Initialize your pointers with NULL! Now, there is no BUG.

ספטמבר 04Copyright Meir Kalech16 String Allocation For array allocation, the programmer gets the size from the user. On the other hand, for string allocation, it doesn ’ t make sense to ask the user for the size, since the meaning of a string size is its number of letters. Therefore, it is common to define a buffer (of length fit for a large string) to store the input string and allocate memory according to the size of the input string.

ספטמבר 04Copyright Meir Kalech17 String Allocation Data segment: Stack segment: ? p1: 100 ? … ????? char *p1, buffer[30]; printf( “ enter string ” ); scanf( “ %s ”, buffer); p1 = (char *) malloc(strlen(buffer)+1); strcpy(p1, buffer); free(p1); buffer: 200

ספטמבר 04Copyright Meir Kalech18 char *p1, buffer[30]; printf( “ enter string ” ); scanf( “ %s ”, buffer); p1 = (char *) malloc(strlen(buffer)+1); strcpy(p1, buffer); free(p1); String Allocation Data segment: Stack segment: ? p1: 100 ? … \0 noiz buffer: 200 Input: “ zion ”

ספטמבר 04Copyright Meir Kalech19 char *p1, buffer[30]; printf( “ enter string ” ); scanf( “ %s ”, buffer); p1 = (char *) malloc(strlen(buffer)+1); strcpy(p1, buffer); free(p1); String Allocation Data segment: Stack segment: 500 p1: 100 ? … \0 noiz buffer: 200 ? ???? 500

ספטמבר 04Copyright Meir Kalech20 char *p1, buffer[30]; printf( “ enter string ” ); scanf( “ %s ”, buffer); p1 = (char *) malloc(strlen(buffer)+1); strcpy(p1, buffer); free(p1); String Allocation Data segment: Stack segment: 500 p1: 100 ? … \0 noiz buffer: 200 \0 noiz 500

ספטמבר 04Copyright Meir Kalech21 char *p1, buffer[30]; printf( “ enter string ” ); scanf( “ %s ”, buffer); p1 = (char *) malloc(strlen(buffer)+1); strcpy(p1, buffer); free(p1); String Allocation Data segment: Stack segment: 500 p1: 100 ? … \0 noiz buffer: 200

ספטמבר 04Copyright Meir Kalech22 realloc Function One of the goals of dynamic memory allocation is to enable reallocation, namely, increase/decrease the old allocation size. There is reallocation function called realloc. Example: int size, size2; int *pointer; printf(“how many integers?”); scanf(“%d”, &size); pointer = (int *) malloc(size*sizeof(int)); if(pointer == NULL) exit(1); printf(“how many integers more?”); scanf(“%d”, &size2); pointer = (int *) realloc(pointer,(size+size2)*sizeof(int)); if(pointer == NULL) exit(1);

ספטמבר 04Copyright Meir Kalech23 realloc Function Some Comments: 1. The new size is the old + additional size. 2. The process: If there is enough space extend the old allocation. Else Allocate new size (old + additional ). Copy the old data to the new place. Free the old allocation (should not be used anymore). Return the first address of the allocation. 3. If the first parameter is NULL, then just malloc.

ספטמבר 04Copyright Meir Kalech24 Array of Pointers The problem: Assume we want to read a list of 3 names. The names differ in length but the maximum name length is 23. First solution: char arr[3][23]; A list of names is an array of strings. Since a string is an array of char, we have a 2D array of char. Can cause waste of memory!!! Snowwhite\0 Littleredridinghood Cinderella

ספטמבר 04Copyright Meir Kalech25 Array of Pointers Second solution: char * arr[3]; arr is array of 3 elements, where each of them is a pointer to char. Now each element can point to a different char array of a different size. \0etihw wonS \0dooh gnidir der el ttiL allere dniC arr: 100

ספטמבר 04Copyright Meir Kalech26 Pointer to Pointer Sometimes the number of rows (names) is unknown ahead of time. In this case, we should allocate both the rows as well as the elements of each vector: 1. Allocate array of pointers. 2. Allocate each pointer in the array.

ספטמבר 04Copyright Meir Kalech27 Pointer to Pointer char **ppChar = NULL, buffer[30]; int num; 0 ppChar: 100 ? num: 120 ? … ? ???? buffer: 900

ספטמבר 04Copyright Meir Kalech28 Pointer to Pointer char **ppChar = NULL, buffer[30]; int num; printf( “ how many names? ” ); scanf( “ %d ”, &num); ppChar = (char **) calloc(num, sizeof(char *)); 150 ppChar: num: 120 INPUT: … buffer: 900

ספטמבר 04Copyright Meir Kalech29 Pointer to Pointer char **ppChar = NULL, buffer[30]; int num,i; printf( “ how many names? ” ); scanf( “ %d ”, &num); ppChar = (char **) calloc(num, sizeof(char *)); for(i=0; i<num; i++) { scanf( “ %s ”, buffer); ppChar[i] = (char *) malloc(strlen(buffer)+1); strcpy(ppChar[i], buffer); } 150 ppChar: num: … \0 WONS buffer: 900 \0 WONS 200

ספטמבר 04Copyright Meir Kalech30 Pointer to Pointer 150 ppChar: num: … ? \0DER buffer: 900 \0 WONS 200 \0 DER 340 char **ppChar = NULL, buffer[30]; int num,i; printf( “ how many names? ” ); scanf( “ %d ”, &num); ppChar = (char **) calloc(num, sizeof(char *)); for(i=0; i<num; i++) { scanf( “ %s ”, buffer); ppChar[i] = (char *) malloc(strlen(buffer)+1); strcpy(ppChar[i], buffer); }

ספטמבר 04Copyright Meir Kalech31 Pointer to Pointer 150 ppChar: num: buffer: 900 \0 WONS 200 \0 DER \0ALLERE DNIC ? … ALLERE DNIC char** ppChar = NULL, buffer[30]; int num,i; printf( “ how many names? ” ); scanf( “ %d ”, &num); ppChar = (char **) calloc(num, sizeof(char *)); for(i=0; i<num; i++) { scanf( “ %s ”, buffer); ppChar[i] = (char *) malloc(strlen(buffer)+1); strcpy(ppChar[i], buffer); }

ספטמבר 04Copyright Meir Kalech32 Pointer to Pointer - free for(i=0; i<num; i++) free(ppChar[i]); 150 ppChar: num: buffer: 900 \0 WONS 200 \0 DER \0ALLERE DNIC ? … ALLERE DNIC

ספטמבר 04Copyright Meir Kalech33 Pointer to Pointer - free for(i=0; i<num; i++) free(ppChar[i]); 150 ppChar: num: buffer: 900 ? … \0ALLERE DNIC

ספטמבר 04Copyright Meir Kalech34 Pointer to Pointer - free for(i=0; i<num; i++) free(ppChar[i]); free(ppChar); 150 ppChar: num: 120 buffer: 900 ? … \0ALLERE DNIC

ספטמבר 04Copyright Meir Kalech35 Dynamic Memory Allocation - Function How to allocate memory in a function? Problem: indeed DMA lifetime does not depend on the function, but the scope and lifetime of the pointer to the memory is only in the function! So how to use the allocated memory also outside the function? Solution: Return the pointer from the function. Pass the pointer by address.

ספטמבר 04Copyright Meir Kalech36 Problem void func() { int *p; p = (int *) calloc(3,sizeof(int)); } void main() { func(); // how to use p here??? } 100 HEAP: 000 STACK: main

ספטמבר 04Copyright Meir Kalech37 Return Address int *func() { int *p; p = (int *) calloc(3,sizeof(int)); return p; } void main() { int *pm = func(); } main HEAP: 000 STACK: pm:

ספטמבר 04Copyright Meir Kalech38 Pass Address void func(int *p) { p = (int *) calloc(3,sizeof(int)); } void main() { int* pm = NULL; func(pm); // how to use p here??? } main HEAP: STACK: pm: 250 0

ספטמבר 04Copyright Meir Kalech39 Pass Address void func(int *p) { p = (int *) calloc(3,sizeof(int)); } void main() { int *pm = NULL; func(pm); // how to use p here??? } func HEAP: STACK: main pm: p: 400 0

ספטמבר 04Copyright Meir Kalech40 Pass Address void func(int *p) { p = (int *) calloc(3,sizeof(int)); } void main() { int *pm = NULL; func(pm); } HEAP: func STACK: main pm: p:

ספטמבר 04Copyright Meir Kalech41 Pass Address – Right Way void func(int **p) { *p = (int *) calloc(3,sizeof(int)); } void main() { int *pm = NULL; func(&pm); } HEAP: func STACK: main pm: p:

ספטמבר 04Copyright Meir Kalech42 Pass Address – Right Way void func(int **p) { *p = (int *) calloc(3,sizeof(int)); } void main() { int *pm = NULL; func(&pm); } HEAP: If a parameter (pointer) is changed in a function ( “ p = “ ), it must be passed by address. If its pointed value is changed ( “ p[i] = “ ), it can be passed by value. func STACK: main pm: p: