DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.

Slides:



Advertisements
Similar presentations
Pointers.
Advertisements

Dynamic memory allocation
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.
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.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Dynamic Memory Allocation
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.
CSE 251 Dr. Charles B. Owen Programming in C1 Dynamic Memory Allocation Dynamic memory allocation – How to allocate memory for variables (esp. arrays/strings)
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
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.
ספטמבר 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.
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:
Winter2015 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University C: Advanced Topics.
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 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.
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
Lecture 2 Pointers Pointers with Arrays Dynamic Memory Allocation.
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.
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
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
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,
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
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.
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
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.
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.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
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 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.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
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
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:
CSCI206 - Computer Organization & Programming
Programming and Data Structures
CSC215 Lecture Memory Management.
Dynamic Memory Allocation
Dynamic Memory Allocation
CS111 Computer Programming
Dynamic Memory Allocation
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
C Programming Lecture-8 Pointers and Memory Management
Chapter 10-1: Dynamic Memory Allocation
C Structures and Memory Allocation
Module 13 Dynamic Memory.
Presentation transcript:

DYNAMIC MEMORY ALLOCATION

Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements declared is 30 for an array, say int test[30], but the user manipulates with only 10 elements, then the space for 20 elements is wasted. DIFFERENT DATA TYPES COULD NOT BE STORED IN AN ARRAY

 The use of pointer variable instead of arrays, helps in allocation of memory at RUN TIME, thus memory can be allocated or freed anywhere, anytime during the program execution. This is known as DYNAMIC MEMORY ALLOCATION

STATIC vs DYNAMIC The allocation of memory for the specific fixed purposes of a program in a predetermined fashion controlled by the compiler is said to be static memory allocation. The allocation of memory (and possibly it’s later de allocation) during the run time of a program and under the control of the program is said to be dynamic memory allocation.

Memory Allocation Functions The following are four memory management functions defined in library of C that can be used for allocation and freeing of memory when ever required. »malloc »calloc »free »realloc All the above four functions are defined in library file.

malloc ( )  malloc : It is a predefined library function that allocates requested size of bytes and returns a pointer to the first byte of the allocated space.  Pointer returned is of type void that has to be type cast to the type of memory block created (int, char, float, double).  General syntax: ptr = (cast –type * ) malloc( byte-size ) ; where ptr is pointer of any data type. malloc returns a pointer to an area of memory with size byte-size.

Example 1  int *ptr; ptr = (int *) malloc ( 100 * (sizeof (int ) ) ; Allocate 200 bytes i.e declare an array of 100 integers with pointer ptr pointing to the first element of the array Number of elements in the array ptr is pointing to. Returns the size of integer Type cast

Alternative int * ptr ; printf ( “\n Enter the number of elements in the array “); scanf(“%d”, &n); ptr = ( int *) malloc ( n x sizeof ( int ) ) ; int * ptr ; ptr = ( int *) malloc ( 200 ) ;

Example 2 char * cptr ; cptr = ( char * ) malloc ( 10 ) ; This will allocate 10 bytes of memory space for the pointer cptr of type char. 10 bytes of space cptr pointer holding the address of the first byte of the array of 10 elements ? ? ? ? ?

Important  The storage space allocated dynamically has NO name and therefore its contents are accessed ONLY through a pointer.  malloc allocates blocks of contiguous memory locations.  If allocation fails due to in sufficient space, it returns NULL pointer. Thus when ever we allocate memory it should be checked whether the memory has assigned successfully or not.

Exercise  Write a program to create an array of integers.Size of the array that is number of elements in the array will be specified interactively by the user at RUN TIME.

Visualization If size = 10 => 20 bytes will be allocated. Integer pointer * table pointing to first element of array

SOLUTION : Reading values in the array // reading values in array printf(“\n Input table value “); for( p= table; p<table + size ; p++) scanf(“%d”, p ); // no ampersand as p is pointer // printing values of array in reverse order for( p = table+size – 1 ; p >= table ; p-- ) printf(“%d”, *p);

Visualization table pointer * p for( p= table; p<table + size ; p++) scanf(“%d”, p ); pointer * p

Printing values in reverse order * table for( p = table+size – 1 ; p >= table ; p-- ) printf(“ %d”, *p); pointer * p

OUTPUT What is the size of array ? 5 Address of first byte : 077FA Input values: OUTPUT values in reverse order

calloc ( )  calloc ( ): It also allocates the requested number of bytes, but the difference is that it takes two parameters: »N : number of elements »Element_size: size of element in bytes  Also when the memory is allocated, all the elements are assigned a initial value of zero.  This is not provided by function malloc ( ) General syntax: ptr = (cast _type * ) calloc (n, element_size);

 The above statement allocates contiguous space for n elements, each of size element_size.  All elements are initialized to zero and a pointer to the first byte of the allocated region is returned.  If there is not enough space, a NULL pointer is returned.

Releasing the Used Space  In case of Dynamic RUN Time allocation, it is the responsibility of the programmer to release the memory space when it is not required by the program.  When a block of data in memory is no longer needed by the program, it should be released as memory is a factor in executing complex programs.

free ( )  To release the memory currently allocated to a pointer using DYNAMIC ALLOCATION use the following function: free ( ptr ); where ptr is a pointer to a memory block which has already been created using either malloc or calloc.

Altering the size of memory block  REALLOCATION function (realloc)

Example  If the original allocation was done by the statement: ptr = (cast_type * ) malloc ( size ) ;  Then REALLOCATION of space is done by : ptr = (cast_type * )realloc ( ptr, NEW_SIZE );

How It works ? ? ?  This function allocates a new memory space of size NEW_SIZE to the pointer variable ptr and returns a pointer to the first byte of the new memory block.  The NEW_SIZE may be larger or smaller than the original size.  The new block of memory MAY or MAY NOT begin at the same place as the previously allocated memory block.

 The function guarantees that the old data will remain intact, if it run successfully.  If the function is unsuccessful in locating additional space, it returns a NULL pointer and the original block is FREED [ lost ].

Memory allocation function If memory allocation fails, these functions return a NULL pointer. Since these functions return a pointer to void, when allocating memory use conversion: pi = (int*)malloc(5*sizeof(int)); /* or */ pi = (int*)calloc(5, sizeof(int)); pi = (int*)realloc(pi, 10*sizeof(int));

Exercise  Write a program to store a character string in a block of memory space created by malloc and then modify the same to store a larger string.

SOLUTION int main(void) { char * buffer ; /* allocating memory */ if( (buffer = (char *) malloc (10 ))== NULL ) { printf(“ NOT ENOUGH SPACE “ ); exit (1 ); } strcpy(buffer, “ NOIDA “ ); /* reallocating space */ if ( (buffer = (char *) realloc( buffer, 15 ) ) == NULL ) {printf(“ REALLOCATION FAILS “); exit (1 ); }

Two dimensional Array  In the same manner it is also possible to create a two dimensional array at RUN TIME using malloc ( ) or calloc ( ).  For creating a two dimensional array, declare a pointer as follows: data_type ** pointer ; example: int **p;

ptr[0] ptr[1] ptr[2] ptr[3] ptr[4] int **ptr

Check This Out !!!  Is it possible to create a TWO Dimensional array with m rows, where each row will have different number of columns ? ? ? YES ! ! !

Visualization

Linked List  A linked list a bunch of structs all connected by pointers.  There are basically two types of linked lists: single and double.  In a single linked list, each node in the list is a struct and contains data plus a pointer to the next node.

 Linked lists are a way to store data with structures automatically create a new place to store data whenever necessary  Specifically, a struct definition scontains – variables holding information about something, and – has a pointer to a struct of its type. –Each of these individual struct in the list is commonly known as a node –Data - - Data - – –Pointer > - Pointer- –

Think of it like a train.  The programmer always stores the first node of the list.  This would be the engine of the train.  The pointer is the connector between cars of the train.  Every time the train adds a car, it uses the connectors to add a new car. This is like a programmer using the malloc / calloc to create a pointer to a new struct.

 struct node {  int x;  node *next; };  int main(){  node *root; // This will be the unchanging first node  root = (node*)malloc(sizeof(node)); // Now root points to a node struct  root->next = 0; // The node root points to has its next pointer set equal to a null pointer  root->x = 5; // By using the -> operator, you can modify the node // a pointer (root in this case) points to.

Think back to the train.  Lets imagine a conductor who can only enter the train through the engine, and can walk through the train down the line as long as the connector connects to another car.  This is how the program will traverse the linked list.  The conductor will be a pointer to node, and it will first point to root, and then, if the root's pointer to the next node is pointing to something, the "conductor" (not a technical term) will be set to point to the next node.  In this fashion, the list can be traversed.  Now, as long as there is a pointer to something, the traversal will continue.  Once it reaches a null pointer (or dummy node), meaning there are no more nodes (train cars) then it will be at the end of the list, and a new node can subsequently be added if so desired.

 struct node  { int x; node *next;};  int main()  { node *root; // This won't change, or we would lose the list in memory  node *conductor; // This will point to each node as it traverses the list  root = (node*)malloc(sizeof(node)); // Sets it to actually point to something  root->next = 0; // Otherwise it would not work well  root->x = 12;  //code to traverse a list  conductor = root; // The conductor points to the first node  if ( conductor != 0 )  { while ( conductor->next != 0)  conductor = conductor->next;  }

 Code to insert node at end  conductor->next = (node*)malloc(sizeof(node)); // Creates a node at the end of the list  conductor = conductor->next; // Points to that node  conductor->next = 0; // Prevents it from going any further  conductor->x = 42;}