Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Structures and Algorithms Memory allocation and Dynamic Array

Similar presentations


Presentation on theme: "Data Structures and Algorithms Memory allocation and Dynamic Array"— Presentation transcript:

1 Data Structures and Algorithms Memory allocation and Dynamic Array
Dr. Muhammad Safyan Department of computer Science Government College University, Lahore

2 What operations complier do when a object is created?

3 Object creation When a C++ object is created, two events occur: 1. Storage is allocated for the object. 2. The constructor is called to initialize that storage. By now you should believe that step two always happens. C++ enforces it because uninitialized objects are a major source of program bugs. It doesn’t matter where or how the object is created – the constructor is always called.

4 Step one, however, can occur in several ways, or at alternate times:
Storage can be allocated before the program begins, in the static storage area. This storage exists for the life of the program. Storage can be created on the stack whenever a particular execution point is reached (an opening brace). That storage is released automatically at the complementary execution point (the closing brace). These stack-allocation operations are built into the instruction set of the processor and are very efficient. However, you have to know exactly how many variables you need when you’re writing the program so the compiler can generate the right code. Storage can be allocated from a pool of memory called the heap (also known as the free store). This is called dynamic memory allocation. To allocate this memory, a function is called at runtime; this means you can decide at any time that you want some memory and how much you need. You are also responsible for determining when to release thememory, which means the lifetime of that memory can be as long as you choose – it isn’t determined by scope

5 Heap MEMORY STACK Static storage area Function calls Objects Arrays
Often these three regions are placed in a single contiguous piece of physical memory: the static area, the stack, and the heap (in an order determined by the compiler writer)

6 operator new The solution in C++ is to combine all the actions necessary to create an object into a single operator called new. When you create an object with new (using a new-expression), it allocates enough storage on the heap to hold the object and calls the constructor for that storage. Thus, if you say MyType *fp = new MyType(1,2); the constructor for MyType is called with the resulting address as the this pointer, using (1,2) as the argument list. By the time the pointer is assigned to fp, it’s a live, initialized object. It’s also automatically the proper MyType type so no cast is necessary.

7 operator delete The complement to the new-expression is the delete- expression, which first calls the destructor and then releases the memory (often with a call to free( )). Just as a new-expression returns a pointer to the object, a delete-expression requires the address of an object. delete fp; This destructs and then releases the storage for the dynamically allocated MyType object created earlier. delete can be called only for an object created by new.

8 Memory Management Static memory:
This memory is allocated at compile time. This memory is located on stack. int i; Memory is acquired automatically. Memory is returned automatically when object goes out of scope. Dynamic memory: This memory is allocated at runtime. This memory is located on heap. int *p = new int; Memory is acquired by program with an allocation request: new operator Dynamic objects can exist beyond the function in which they were allocated Object memory is returned by a deallocation request: Delete operator

9 ”new” operator and ”delete” operator
new, requests for unnamed memory from operating system. Syntax: ptr = new sometype Example: 1 2 3 4 5 6 7 8 9 i n t * p t r= new i n t ; c h a r ∗ c p t r = new c h a r ; Po in t ∗ p3 = new Po i n t ; i n t ∗ p , n = ; p = new i n t [ n ] ; c in >>p [ 2 ] ; delete, storage pointed to by a pointer is returned to free store and pointer is now undefined. Syntax: delete pointername Example: 1 2 3 d e l e t e p t r ; d e l e t e [ ] p ;

10 ”delete” operator

11 Dangling pointer i n t ∗A = new i n t [ 5 ] ; i <5; i ++) 1 f o r ( i n t i =0; A[ i ] = i ; 2 3 i n t ∗B = A; 4 5 d e l e t e [ ] A; B [ 0 ] = 1 ; // i l l e g a l ! 6 7 Dangling pointers arise when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory.

12 Memory leak i n t ∗A = new i n t [ 5 ] ; 1 f o r ( i n t i =0; i <5; i ++) A[ i ] = i ; A = new i n t [ 5 ] ; 2 3 4 5 e A memory leak, in computer science (or leakage, in this context), occurs when a computer program consumes memory but is unable to release it back to the operating system. e In object-oriented programming, a memory leak happens when an object is stored in memory but cannot be accessed by the running code

13 Drawback of array

14 Dynamic Arrays

15 Using operator new If memory is available in an area called the free store (or heap), operator new allocates the requested object, and returns a pointer to the memory allocated. The dynamically allocated object exists until the delete operator destroys it.

16 Why is a destructor needed?
When a local stack variable goes out of scope, the memory space for data member topPtr is deallocated. But the nodes that topPtr points to are not automatically deallocated. A class destructor is used to deallocate the dynamic memory pointed to by the data member.

17 What is a List? A list is a homogeneous collection of elements, with a linear relationship between elements. That is, each list element (except the first) has a unique predecessor, and each element (except the last) has a unique successor.

18 ADT Unsorted List Operations
Transformers MakeEmpty InsertItem DeleteItem Observers IsFull LengthIs RetrieveItem Iterators ResetList GetNextItem change state observe state process all

19 #include “ItemType.h” // unsorted.h template <class ItemType>
template <class ItemType> class UnsortedType { public : // LINKED LIST IMPLEMENTATION UnsortedType ( ) ; ~UnsortedType ( ) ; void MakeEmpty ( ) ; bool IsFull ( ) const ; int LengthIs ( ) const ; void RetrieveItem ( ItemType& item, bool& found ) ; void InsertItem ( ItemType item ) ; void DeleteItem ( ItemType item ) ; void ResetList ( ); void GetNextItem ( ItemType& item ) ; private : NodeType<ItemType>* listData; int length; NodeType<ItemType>* currentPos; } ;

20 class UnsortedType<char>
Private data: length listData currentPos MakeEmpty ~UnsortedType ‘X’ ‘C’ ‘L’ RetrieveItem InsertItem DeleteItem . GetNextItem

21 // LINKED LIST IMPLEMENTATION ( unsorted.cpp )
#include “itemtype.h” template <class ItemType> UnsortedType<ItemType>::UnsortedType ( ) // constructor // Pre: None. // Post: List is empty. { length = 0 ; listData = NULL; } int UnsortedType<ItemType>::LengthIs ( ) const // Post: Function value = number of items in the list. return length;

22 template <class ItemType>
void UnsortedType<ItemType>::RetrieveItem( ItemType& item, bool& found ) // Pre: Key member of item is initialized. // Post: If found, item’s key matches an element’s key in the list and a copy // of that element has been stored in item; otherwise, item is unchanged. { bool moreToSearch ; NodeType<ItemType>* location ; location = listData ; found = false ; moreToSearch = ( location != NULL ) ; while ( moreToSearch && !found ) { if ( item == location->info ) // match here { found = true ; item = location->info ; } else // advance pointer { location = location->next ; moreToSearch = ( location != NULL ) ; }}} 22

23 template <class ItemType>
void UnsortedType<ItemType>::InsertItem ( ItemType item ) // Pre: list is not full and item is not in list. // Post: item is in the list; length has been incremented. { NodeType<ItemType>* location ; // obtain and fill a node location = new NodeType<ItemType> ; location->info = item ; location->next = listData ; listData = location ; length++ ; } 23

24 Inserting ‘B’ into an Unsorted List
‘X’ ‘C’ ‘L’ Private data: length listData currentPos

25 location = new NodeType<ItemType>;
‘B’ location = new NodeType<ItemType>; item location ‘X’ ‘C’ ‘L’ Private data: length listData currentPos

26 location->info = item ;
‘B’ location->info = item ; item location ‘B’ ‘X’ ‘C’ ‘L’ Private data: length listData currentPos

27 location->next = listData ;
‘B’ location->next = listData ; item location ‘B’ ‘X’ ‘C’ ‘L’ Private data: length listData currentPos

28 listData = location ; ‘B’ item location ‘B’ Private data: length 3
currentPos ‘X’ ‘C’ ‘L’

29 length++ ; ‘B’ item location ‘B’ Private data: length 4 listData
currentPos ‘X’ ‘C’ ‘L’

30 class SortedType<char>
Private data: length listData currentPos MakeEmpty ~SortedType ‘C’ ‘L’ ‘X’ RetrieveItem InsertItem DeleteItem . GetNextItem

31 InsertItem algorithm for Sorted Linked List
Find proper position for the new element in the sorted list using two pointers predLoc and location, where predLoc trails behind location. Obtain a node for insertion and place item in it. Insert the node by adjusting pointers. Increment length.

32 Implementing SortedType member function InsertItem
// LINKED LIST IMPLEMENTATION (sorted.cpp) #include “ItemType.h” template <class ItemType> void SortedType<ItemType> :: InsertItem ( ItemType item ) // Pre: List has been initialized. List is not full. item is not in list. // List is sorted by key member. // Post: item is in the list. List is still sorted. { . }

33 Inserting ‘S’ into a Sorted List
predLoc location Private data: length listData currentPos ‘C’ ‘L’ ‘X’ moreToSearch

34 Finding proper position for ‘S’
predLoc location NULL Private data: length listData currentPos ‘C’ ‘L’ ‘X’ moreToSearch true

35 Finding proper position for ‘S’
predLoc location Private data: length listData currentPos ‘C’ ‘L’ ‘X’ moreToSearch true

36 Finding proper position for ‘S’
predLoc location Private data: length listData currentPos ‘C’ ‘L’ ‘X’ moreToSearch false

37 Inserting ‘S’ into proper position
predLoc location Private data: length listData currentPos ‘C’ ‘L’ ‘X’ ‘S’ moreToSearch false


Download ppt "Data Structures and Algorithms Memory allocation and Dynamic Array"

Similar presentations


Ads by Google