DYNAMIC MEMORY MANAGEMENT. int x; When the source code containing this statement is compiled and linked, an executable file is generated. When the executable.

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

Introduction to Linked Lists In your previous programming course, you saw how data is organized and processed sequentially using an array. You probably.
Dynamic Memory Allocation (also see pointers lectures) -L. Grewe.
Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
1 CSC241: Object Oriented Programming Lecture No 28.
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:
Dynamic memory allocation. The process of allocating memory at run time is known as dynamic memory allocation. C have four library functions for allocating.
CS Advanced C++ Exception Handling Topic #5.
Informática II Prof. Dr. Gustavo Patiño MJ
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
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.
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Pointers Applications
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
February 11, 2005 More Pointers Dynamic Memory Allocation.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
Pointers CSE 5100 Data Structures and Algorithms.
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,
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
Pointers review Let a variable aa be defined as ‘int *aa;’, what is stored in aa? Let a variable aa be defined as ‘int ** aa;’ what is stored in aa? Why.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
Object-Oriented Programming in C++
Dynamic memory allocation and Pointers Lecture 4.
Pointers and Dynamic Memory Allocation. Declaring a pointer.
1 Pointers to structs. 2 A pointer to a struct is used in the same way as a pointer to a simple type, such as an int. Pointers to structs were introduced.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Review 1 List Data Structure List operations List Implementation Array Linked List.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
C++ 程序语言设计 Chapter 12: Dynamic Object Creation. Outline  Object creation process  Overloading new & delete.
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 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 24: Pointers and Dynamic Allocation.
Exception Handling How to handle the runtime errors.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
CSC Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Exception handling.
Introduction to Programming
Pointers Revisited What is variable address, name, value?
Dynamically Allocated Memory
Dynamic Memory Allocation
An Introduction to Pointers
Pointers, Dynamic Data, and Reference Types
Dynamic Memory Allocation
Advanced C++ Exception Handling
Dynamic Memory.
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
DYNAMIC MEMORY MANAGEMENT
Pointers, Dynamic Data, and Reference Types
More C++ Classes Systems Programming.
Module 13 Dynamic Memory.
Presentation transcript:

DYNAMIC MEMORY MANAGEMENT

int x; When the source code containing this statement is compiled and linked, an executable file is generated. When the executable file is executed, instruction for allocating the memory for ‘x’ is executed and memory gets allocated for ‘x’. This is known as ‘static memory allocation’ although memory gets allocated at run time. During execution, the instruction to deallocate memory for ‘x’ is executed and memory gets deallocated (static deallocation) The programmers are forced to predict the total amount of data the program will utilize. Statements are written to declare pre-calculated amount of memory. During run time, if memory is required, static memory allocation can not fulfill the need.

Memory allocated cannot be released immediately, although it is not used. It will be held up until the end of block execution Dynamic memory management overcomes the drawback of static memory allocation. Memory gets allocated and deallocated during runtime only. The decisions to do so can be taken dynamically in response to the requirements arising during runtime itself Dynamic memory allocation It is achieved in C through malloc(), calloc() and realloc() functions In C++ it is achieved through ‘new’ operator

#include void main() { int * iPtr; iPtr= new int ; *iPtr = 10; cout << *iPtr << endl; } // end of dynamic.cpp Output : 10

‘new’ takes a predefined data type as an operand. It then allocates memory to hold one value of the data type that is passed as a parameter in the heap. Finally it returns the address of the allocated block(need not be type casted). This address can be stored in a pointer and can be accessed through it The general syntax is = new The new operator can be used to create multiple blocks of memory also = new [ ]

#include # define SIZE 10 void main() { int * iPtr; iPtr= new int [SIZE] ; for ( int i = 0 ; i < SIZE ; i++) iPtr [i] = i ; for ( int i = 0 ; i < SIZE ; i++) cout << iPtr [i] << endl ; } // end of dynarr1.cpp Output: 0 to 9 in subsequent lines

#include //size specified at runtime void main() { int * iPtr; unsigned int isize ; cout <<“Enter the size of the array: “; cin >> isize ; iPtr= new int [isize] ; for ( int i = 0 ; i < isize ; i++) { cout << “Enter the value for element “<<i+1<<“:“; cin >> iPtr [i] ; } for ( int i = 0 ; i < SIZE ; i++) cout << iPtr [i] << endl ; } // end of dynarr2.cpp

#include //array of objects #include”Distance.h” void main() { Distance * dPtr; int a; float b; unsigned int isize ; cout <<“Enter the number of the elements: “; cin >> isize ; dPtr= new Distance [isize] ; for ( int i = 0 ; i < isize ; i++) { cout << “Enter the feet : “ ; cin >> a ;

cout << “Enter the inches : “ ; cin >> b ; dPtr[i]. setFeet(a); dPtr[i]. Setnches(b); } for ( int i = 0 ; i < SIZE ; i++) cout << dPtr [i].getFeet() << “ ” << dPtr[i].getInches()<< endl ; } // end of dyndist.cpp The amount of memory to be allocated is being decided during runtime itself.

Dynamic memory deallocation Once the allocated memory is not in use any more, it should be returned to the OS It is achieved through the free() function in C In C++, through the delete operator General syntax – delete The memory block will be deallocated only at the end of the functions that allocates it. However, it is usually conditional Misconception about delete – the memory being occupied by the pointer itself gets removed if the delete operator is used on the pointer

#include void abc(); void main() { abc(); // rest of main() function } void abc() {int *iPtr; iPtr = new int; //rest of abc() function } // end of memleak.cpp

When abc() executes, memory will be allocated and base address is returned which is stored in pointer When abc() finishes execution, ‘iPtr’(pointer) itself is deallocated, but the memory in the heap area remains locked up as an orphan. This is known as memory leak. This block of memory can not be accessed since the only pointer was removed from the stack It can be deallocated by passing the pointer pointing to it as an operand to the delete operator delete iPtr; is executed just before the abc() function terminates and memory leak is prevented

When the delete operator is used on the pointer that points at this block of memory, it gets deallocated and made available for the OS The block of memory locked up by the code in a certain function persists even after the function terminates is frequently desirable and can have a reference void abc ( int ** p) { // some complex algorithm *p = new int ; // rest of abc() function }

void main () { int * iPtr ; abc (& iPtr ) // rest of main function } A block of memory is allocated and its address is stored in ‘iPtr’ by dereferencing the pointer that points at it After abc() terminates, ‘iPtr’ that is a local variable in the calling function will point at the dynamically allocated block of memory

void abc ( int ** p) { if (memory_not_required) { delete * p; *p = null ; } // rest of abc() function } When the delete operator is used on a pointer, the pointer continues to occupy its own block of memory and continues to have the same value, the address of the memory that has just get deallocated. This will lead to runtime errors if the pointer is dereferenced

The pointer being pointed at by ‘p’ was deliberately nullified after the memory has been deallocated It is highly desirable that either the pointer points at a valid dynamically allocated block or be NULL. But it is not possible to ensure this There is no guaranteed initialization of data A multiple block of memory is deallocated by suffixing delete operator with [] followed by the pointer - delete[] ; Distance * dPtr ; dPtr = new Distance[5] ;//creates an array delete [] dPtr ; // deallocates the memory

Set_new_handler() function When new operator attempts to allocate memory from the heap and memory is not available, we get an out-of-memory condition Then with the help of new handler function, it throws an exception of type ‘bad_alloc’ We can specify that the new operator, upon encountering such condition, to call ‘set_new_handler()’ function and to pass the name of the desired function as parameter to it This prototype is in the ‘new.h’ header file new_handler set_new_handler (new_handler)

It is a data type and a function pointer type The formal argument is a function pointer If we pass the name of our desired function as a parameter to the function, all subsequent out-of- memory conditions cause the new operator to call it. Our desired function becomes the new handler When the set_new_handler() function is called, it returns a pointer to the previous new handler function An important characteristic of the new operator is that when its request for memory fails, it calls the new handler function repeatedly until its request is satisfied

#define BIG_NUMBER #include //specifying new handler function void myNewHandler() { //code to handle out-of-memory condition} void main() { new_handler oldHandler; //set function myNewHandler as new handler oldHandler=set_new_handler(myNewHandler); int * p =new int[BIG_NUMBER]; //probably cause } //out of memory

If the OS is unable to allocate the required amount of memory, the new operator fails. The new handler function gets called. Since myNewHandler is set as the new handler, it gets called We can make the function log an error message and then call the abort() which simply terminates the program void myNewHandler() { //statement to log a suitable error message abort(); // terminates the program } //defining new handler function

We can replace the existing new handler function by another one. For this, we can call the ‘set_new_handler()’ from with in the existing new handler. Such a call to be preceded by the code that attempts to resolve out-of memory condition #include //replacing existing new_han_fun void myNewHandler() { // make an attempt to resolve the out-of-memory condition if(above_attempt_fails) set_new_handler (myAnotherNewHandler); }