Dynamic Memory Allocation

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.
CSC 270 – Survey of Programming Languages C Lecture 6 – Pointers and Dynamic Arrays Modified from Dr. Siegfried.
Programming and Data Structure
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.
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.
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.
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:
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{
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 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’;
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
1 Chapter 9 Arrays and Pointers. 2  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
1 Programming with Pointers Turgay Korkmaz Office: SB Phone: (210) Fax: (210) web:
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Lecture 13 Static vs Dynamic Memory Allocation
7. Pointers, Dynamic Memory 20 th September IIT Kanpur 1C Course, Programming club, Fall 2008.
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,
6. More on Pointers 14 th September IIT Kanpur C Course, Programming club, Fall
1 Pointers and Arrays. 2 When an array is declared,  The compiler allocates sufficient amount of storage to contain all the elements of the array in.
14/3/02 Sudeshna Sarkar, CSE, IIT Kharagpur1 Structures, ADT Lecture 25 14/3/2002.
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.
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:
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
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.
ECE Application Programming Instructors: Dr. Michael Geiger & Nasibeh Nasiri Fall 2015 Lecture 31: Structures (cont.) Dynamic memory allocation.
Pointers PART - 2. Pointers Pointers are variables that contain memory addresses as their values. A variable name directly references a value. A pointer.
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.
POINTERS IN C Pointer Basics, Pointer Arithmetic, Pointer to arrays and Pointer in functions.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
1 Linked List. 2 List A list refers to a sequence of data items  Example: An array The array index is used for accessing and manipulation of array elements.
Pointers. Pointer Fundamentals  When a variable is defined the compiler (linker/loader actually) allocates a real memory address for the variable. –int.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
APS105 Malloc and 2D Arrays (text Ch6.4, Ch10.2).
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.
Stack and Heap Memory Stack resident variables include:
Programming Languages and Paradigms
Pointers.
14th September IIT Kanpur
Programming and Data Structures
CSC215 Lecture Memory Management.
Dynamic Memory Allocation
CS111 Computer Programming
Dynamic Memory Allocation
EECE.2160 ECE Application Programming
2-d Arrays.
Linked List.
EECE.2160 ECE Application Programming
C Programming Lecture-8 Pointers and Memory Management
EECE.2160 ECE Application Programming
Programming and Data Structure
Presentation transcript:

Dynamic Memory Allocation

Problem with Arrays Sometimes Amount of data cannot be predicted beforehand Number of data items keeps changing during program execution Example: Seach for an element in an array of N elements One solution: find the maximum possible value of N and allocate an array of N elements Wasteful of memory space, as N may be much smaller in some executions Example: maximum value of N may be 10,000, but a particular run may need to search only among 100 elements Using array of size 10,000 always wastes memory in most cases

Better Solution Dynamic memory allocation Know how much memory is needed after the program is run Example: ask the user to enter from keyboard Dynamically allocate only the amount of memory needed C provides functions to dynamically allocate memory malloc, calloc, realloc

Memory Allocation Functions malloc Allocates requested number of bytes and returns a pointer to the first byte of the allocated space calloc Allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory. free Frees previously allocated space. realloc Modifies the size of previously allocated space. We will only do malloc and free

Allocating a Block of Memory A block of memory can be allocated using the function malloc Reserves a block of memory of specified size and returns a pointer of type void The return pointer can be type-casted to any pointer type General format: type *p; p = (type *) malloc (byte_size);

Example p = (int *) malloc(100 * sizeof(int)); A memory space equivalent to 100 times the size of an int bytes is reserved The address of the first byte of the allocated memory is assigned to the pointer p of type int p 400 bytes of space

Contd. cptr = (char *) malloc (20); Allocates 20 bytes of space for the pointer cptr of type char sptr = (struct stud *) malloc(10*sizeof(struct stud)); Allocates space for a structure array of 10 elements. sptr points to a structure element of type struct stud Always use sizeof operator to find number of bytes for a data type, as it can vary from machine to machine

Points to Note malloc always allocates a block of contiguous bytes The allocation can fail if sufficient contiguous memory space is not available If it fails, malloc returns NULL if ((p = (int *) malloc(100 * sizeof(int))) == NULL) { printf (“\n Memory cannot be allocated”); exit(); }

Using the malloc’d Array Once the memory is allocated, it can be used with pointers, or with array notation Example: int *p, n, i; scanf(“%d”, &n); p = (int *) malloc (n * sizeof(int)); for (i=0; i<n; ++i) scanf(“%d”, &p[i]); The n integers allocated can be accessed as *p, *(p+1), *(p+2),…, *(p+n-1) or just as p[0], p[1], p[2], …,p[n-1]

Example int main() printf("Input heights for %d { students \n",N); int i,N; float *height; float sum=0,avg; printf("Input no. of students\n"); scanf("%d", &N); height = (float *) malloc(N * sizeof(float)); printf("Input heights for %d students \n",N); for (i=0; i<N; i++) scanf ("%f", &height[i]); for(i=0;i<N;i++) sum += height[i]; avg = sum / (float) N; printf("Average height = %f \n", avg); free (height); return 0; }

Releasing the Allocated Space: free An allocated block can be returned to the system for future use by using the free function General syntax: free (ptr); where ptr is a pointer to a memory block which has been previously created using malloc Note that no size needs to be mentioned for the allocated block, the system remembers it for each pointer returned

Can we allocate only arrays? malloc can be used to allocate memory for single variables also p = (int *) malloc (sizeof(int)); Allocates space for a single int, which can be accessed as *p Single variable allocations are just special case of array allocations Array with only one element

malloc( )-ing array of structures typedef struct{ char name[20]; int roll; float SGPA[8], CGPA; } person; void main() { person *student; int i,j,n; scanf("%d", &n); student = (person *)malloc(n*sizeof(person)); for (i=0; i<n; i++) { scanf("%s", student[i].name); scanf("%d", &student[i].roll); for(j=0;j<8;j++) scanf("%f", &student[i].SGPA[j]); scanf("%f", &student[i].CGPA); }

Static array of pointers #define N 20 #define M 10 int main() { char word[N], *w[M]; int i, n; scanf("%d",&n); for (i=0; i<n; ++i) { scanf("%s", word); w[i] = (char *) malloc ((strlen(word)+1)*sizeof(char)); strcpy (w[i], word) ; } for (i=0; i<n; i++) printf("w[%d] = %s \n",i,w[i]); return 0;

Static array of pointers #define N 20 #define M 10 int main() { char word[N], *w[M]; int i, n; scanf("%d",&n); for (i=0; i<n; ++i) { scanf("%s", word); w[i] = (char *) malloc ((strlen(word)+1)*sizeof(char)); strcpy (w[i], word) ; } for (i=0; i<n; i++) printf("w[%d] = %s \n",i,w[i]); return 0; Output 4 Tendulkar Sourav Khan India w[0] = Tendulkar w[1] = Sourav w[2] = Khan w[3] = India

How it will look like w 1 2 3 9 malloc() T e n d u l k a r \0 S o u r T e n d u l k a r \0 1 S o u r a v \0 2 K h a n \0 3 I n d i a \0 9

Pointers to Pointers Pointers are also variables (storing addresses), so they have a memory location, so they also have an address Pointer to pointer – stores the address of a pointer variable int x = 10, *p, **q; p = &x; q = &p; printf(“%d %d %d”, x, *p, *(*q)); will print 10 10 10 (since *q = p)

Allocating Pointer to Pointer int **p; p = (int **) malloc(3 * sizeof(int *)); p p[2] p[1] p[0] int ** int *

2D array #include <stdlib.h> int main() { int **array; array = (int**) malloc(nrows * sizeof(int *)); for(i = 0; i < nrows; i++) array[i] = (int*)malloc(ncolumns * sizeof(int)); }

2D array 1 2 3 9 x Int main() { x *x; } *(x+1); **(x+1); *(*(x+1)+4) Int main() { } 1 2 x 3 *x; *(x+1); **(x+1); *(*(x+1)+4) x[1][0] *(x[3]+7) ??? 9 x[1][4] *((*x)+8) x[0][8]

Dynamic Allocation of 2-d Arrays Recall that address of [i][j]-th element is found by first finding the address of first element of i-th row, then adding j to it Now think of a 2-d array of dimension [M][N] as M 1-d arrays, each with N elements, such that the starting address of the M arrays are contiguous (so the starting address of k-th row can be found by adding 1 to the starting address of (k-1)-th row) This is done by allocating an array p of M pointers, the pointer p[k] to store the starting address of the k-th row

Contd. Now, allocate the M arrays, each of N elements, with p[k] holding the pointer for the k-th row array Now p can be subscripted and used as a 2-d array Address of p[i][j] = *(p+i) + j (note that *(p+i) is a pointer itself, and p is a pointer to a pointer)

Dynamic Allocation of 2-d Arrays int **allocate (int h, int w) { int **p; int i, j; p = (int **) malloc(h*sizeof (int *) ); for (i=0;i<h;i++) p[i] = (int *) malloc(w * sizeof (int)); return(p); } void read_data (int **p, int h, int w) { int i, j; for (i=0;i<h;i++) for (j=0;j<w;j++) scanf ("%d", &p[i][j]); } Elements accessed like 2-D array elements. Allocate array of pointers Allocate array of integers for each row

Contd. void print_data (int **p, int h, int w) { int i, j; for (i=0;i<h;i++) for (j=0;j<w;j++) printf ("%5d ", p[i][j]); printf ("\n"); } int main() { int **p; int M, N; printf ("Give M and N \n"); scanf ("%d%d", &M, &N); p = allocate (M, N); read_data (p, M, N); printf ("\nThe array read as \n"); print_data (p, M, N); return 0; }

Contd. void print_data (int **p, int h, int w) { int i, j; for (i=0;i<h;i++) for (j=0;j<w;j++) printf ("%5d ", p[i][j]); printf ("\n"); } int main() { int **p; int M, N; printf ("Give M and N \n"); scanf ("%d%d", &M, &N); p = allocate (M, N); read_data (p, M, N); printf ("\nThe array read as \n"); print_data (p, M, N); return 0; } Give M and N 3 3 1 2 3 4 5 6 7 8 9 The array read as 1 2 3 4 5 6 7 8 9

Memory Layout in Dynamic Allocation int **allocate (int h, int w) { int **p; int i, j; p = (int **)malloc(h*sizeof (int *)); for (i=0; i<h; i++) printf(“%10d”, &p[i]); printf(“\n\n”); for (i=0;i<h;i++) p[i] = (int *)malloc(w*sizeof(int)); return(p); } int main() { int **p; int M, N; printf ("Give M and N \n"); scanf ("%d%d", &M, &N); p = allocate (M, N); for (i=0;i<M;i++) { for (j=0;j<N;j++) printf ("%10d", &p[i][j]); printf(“\n”); } return 0;

Output Starting address of each row, contiguous (pointers are 8 bytes long) 3 3 31535120 31535128 31535136 31535152 31535156 31535160 31535184 31535188 31535192 31535216 31535220 31535224 Elements in each row are contiguous

Passing pointers to function void foo(int *a) { int m; m=*a; m=m+1; *a=m; } Int main() { int x=5; …………….. ………….. foo(&x); } 5 1400 x a 1400 &x=1400 *a

Call by value Int main() { int x=10, y=5; swap(x,y); } swap(int a, int b) { int temp; temp=a; a=b; b=temp; } 10 5 x y 10 5 a b

Call by Reference Int main() { int x=10, y=5; swap(&x,&y); } swap(int *a, int *b) { int temp; temp=*a; *a=*b; *b=temp; } 1400 10 5 1500 *b x y 1400 1500 *a a b