Presentation is loading. Please wait.

Presentation is loading. Please wait.

Module 13 Dynamic Memory.

Similar presentations


Presentation on theme: "Module 13 Dynamic Memory."— Presentation transcript:

1 Module 13 Dynamic Memory

2 @Copyright UMBC Training Centers 2012
Memory Overview Local variables and function parameters are stored in an area known as “the stack” which is managed by the compiler Dynamic memory is allocated from an area of memory known as “the heap” which must be managed by the programmer @Copyright UMBC Training Centers 2012

3 @Copyright UMBC Training Centers 2012
Why Dynamic Memory In some applications, the size of arrays cannot be known until the application is executing. More complex data structures also require that memory be allocated while our application is running. C provides a set of library functions for dynamically allocating memory during program executing and for releasing the memory for possible reuse. @Copyright UMBC Training Centers 2012

4 @Copyright UMBC Training Centers 2012
Preliminaries sizeof(data_type) – the number of bytes of memory occupied by data_type Use for code portability void* is C’s generic pointer. May only be cast to another type. size_t is the type used for a variable that represents the size of a data type @Copyright UMBC Training Centers 2012

5 @Copyright UMBC Training Centers 2012
Sizeof at Work C::B sizeOf @Copyright UMBC Training Centers 2012

6 @Copyright UMBC Training Centers 2012
malloc( ) void *malloc(size_t nrBytes ); Returns a pointer to dynamically allocated memory on the heap of size nrBytes, or NULL if the request cannot be satisfied. The memory is uninitialized. The returned pointer should be cast to the appropriate type Commonly used for arrays int *ip = (int *) malloc(50 * sizeof(int)); // 50 is had coded, only there to show syntax // 50 would be the size, but that should be dynamic // the space 50 resides would normally be a variable @Copyright UMBC Training Centers 2012

7 @Copyright UMBC Training Centers 2012
Malloc in use From @Copyright UMBC Training Centers 2012

8 @Copyright UMBC Training Centers 2012
calloc( ) void *calloc(int nrElements, size_t elementSz); Allocates memory from the heap and sets it to zero An array of 50 doubles initialized to zero double *dp = (double *)calloc(50, sizeof(double)); // same note as before on 50 @Copyright UMBC Training Centers 2012

9 @Copyright UMBC Training Centers 2012
Calloc() in use @Copyright UMBC Training Centers 2012

10 @Copyright UMBC Training Centers 2012
realloc( ) void *realloc( void *p, size_t nrBytes); Changes the size of the dynamically allocated heap memory pointed to by p to nrBytes The contents of the heap memory pointed to by p will be unchanged up to the minimum of the old and new sizes. int *ip = (int *)calloc(10, sizeof(int)); ip[0] = 42; ip[3] = 57; ip = (int *)realloc(ip, 15 * sizeof(int)); @Copyright UMBC Training Centers 2012

11 @Copyright UMBC Training Centers 2012
Realloc() in use @Copyright UMBC Training Centers 2012

12 @Copyright UMBC Training Centers 2012
Return Values If malloc, calloc or realloc fail to allocate heap memory, their return value is NULL should be checked by your code probably a fatal condition int *ip = (int *)malloc(50 * sizeof(int)); if(ip == NULL) { fprintf(stderr, “malloc failed\n”); exit(EXIT_FAILURE); } @Copyright UMBC Training Centers 2012

13 @Copyright UMBC Training Centers 2012
assert( ) Since failure of malloc, calloc or realloc is usually fatal, we can use assert( ) to test the return value #include <assert.h> assert(Boolean_expression); If Boolean_expression is true, nothing happens If Boolean_expression is false, your program terminates with an appropriate error message int *ip = (int *)malloc(50 * sizeof(int)); assert(ip != NULL); @Copyright UMBC Training Centers 2012

14 @Copyright UMBC Training Centers 2012
free( ) void free(void *p); Deallocates (frees) the heap memory pointed to by p for reuse. p must be a pointer previously returned from malloc, calloc or realloc If p is NULL, free(p) has no effect int *grades; grades = (int *)calloc(45, sizeof(int)); ... free(grades); grades = NULL; @Copyright UMBC Training Centers 2012

15 @Copyright UMBC Training Centers 2012
Let’s take a look C::B MallocTest Only enter 3 weights @Copyright UMBC Training Centers 2012

16 @Copyright UMBC Training Centers 2012
Common Mistakes Using uninitialized dynamic memory Freeing the same memory twice Using memory that was freed Failing to free blocks @Copyright UMBC Training Centers 2012

17 C.M. Using uninitialized memory
int *row, i, value; row = (int *)malloc(4 *sizeof(int)); for (i = 0; i < 50; i++) { printf(“please enter a row: ”); scanf(“%d”, &value); ++row[value % 4]; } @Copyright UMBC Training Centers 2012

18 C.M.  Freeing the same memory twice
double *x, *y; x = (double *)calloc(15, sizeof(double)); free(x); y = (double *)calloc(15, sizeof(double)); @Copyright UMBC Training Centers 2012

19 C.M.  Using memory that was freed
int k, total = 0, *x, *y; x = (int *)malloc(10 * sizeof(int)); free (x); y = (int *)malloc(15 * sizeof(int)); for(k = 0; k < 15; k++) total += x[k]; free(y); @Copyright UMBC Training Centers 2012

20 C.M.  Failing to free blocks
int foo( ) { char *c = (char *)malloc( 20 * sizeof(char)); return 0; } @Copyright UMBC Training Centers 2012

21 @Copyright UMBC Training Centers 2012
Exercises Ex1 @Copyright UMBC Training Centers 2012

22 @Copyright UMBC Training Centers 2012
Dynamic Linked List A dynamic list of homogenous items For simplicity, duplicate items are allow @Copyright UMBC Training Centers 2012

23 @Copyright UMBC Training Centers 2012
Linked List Structure A node contains data and a pointer to the next node The pointer in the last node is NULL (“end of list”) A pointer points to the first node (“head”) typedef struct node { int value; struct node *next; } NODE; static NODE *head; @Copyright UMBC Training Centers 2012

24 @Copyright UMBC Training Centers 2012
Dynamic Linked List Operations Create an empty list Insert – add a new item to the back (front) of the list Remove – remove the first occurrence of an item from the list Find – determine if a specified item is in the list Delete – remove all items from the list @Copyright UMBC Training Centers 2012

25 @Copyright UMBC Training Centers 2012
Create an Empty List An empty list has no nodes set head equal to NULL void createEmptyList( ) { head = NULL; } bool isEmpty( ) return head == NULL; @Copyright UMBC Training Centers 2012

26 @Copyright UMBC Training Centers 2012
Insert an Item Create and initialize a new node Dynamically allocate the node Store the item in the node Set the node’s next pointer to NULL To insert at the end of the list Traverse the list to find the last node Set the last node’s pointer to point to the new node To insert at the front of the list Set the new node’s pointer to point where head points Set head to point to the new node @Copyright UMBC Training Centers 2012

27 @Copyright UMBC Training Centers 2012
Creating a Node NODE *createNode( int value ) { NODE *newNode = (NODE *)malloc(sizeof(NODE)); newNode->data = value; newNode->next = NULL; return newNode; } @Copyright UMBC Training Centers 2012

28 Inserting new node at FRONT
void insertAtFront( int value ) { NODE *newNode = createNode(value); // no special code needed if the list is empty newNode->next = head; // point to current first node if any head = newNode; // new node is now first node } @Copyright UMBC Training Centers 2012

29 Inserting new node at END
void insertAtBack( int value ) { NODE *newNode = createNode(value); // special code if list is empty if (isEmpty()) head = newNode; else { // find the current last node NODE *pNode = head; while (pNode->next != NULL) pNode = pNode->next; pNode->next = newNode; } @Copyright UMBC Training Centers 2012

30 @Copyright UMBC Training Centers 2012
Find an Item in the List If the list is empty, the item can’t be found Set the “current node” pointer to point to the first node While the item has not been found and the current node pointer is not NULL if the item in current node equals the item to be found, we found it Set current node pointer to point to next node in the list If the current node pointer is not NULL, the item was found. If the current node pointer is NULL, the item was not found @Copyright UMBC Training Centers 2012

31 @Copyright UMBC Training Centers 2012
Finding an item @Copyright UMBC Training Centers 2012

32 @Copyright UMBC Training Centers 2012
Finding an item // findItem // if found, returns pointer to first node that contains value // if not found, returns NULL bool findItem( int value ) { NODE *pNode = head; // search for node until found or end of list // handles empty list case while (pNode != NULL && pNode->data != value ) pNode = pNode->next; // pNode points to node with value or is NULL return pNode != NULL; } @Copyright UMBC Training Centers 2012

33 Remove an Item from the List
If the list is empty, nothing to do Else find the item in the list Obtaining a pointer to the node to be removed and a pointer to the node before the node to be removed (the “previous” node) If there is only one item in the list Set head to NULL Otherwise if removing the first item in the list Set head to point to the 2nd node in the list Otherwise if removing the last item in the list Set the previous node’s pointer to NULL In all cases, free the memory for the deleted node @Copyright UMBC Training Centers 2012

34 @Copyright UMBC Training Centers 2012
Removing an Item // remove // returns true if value found and node removed // returns false if value not found bool removeItem( int value ) { NODE *pNode, *prevNode; // can't remove anything if list is empty if (isEmpty( )) return false; // search for node with item // maintain pointer to node before the node with the item prevNode = NULL; pNode = head; while (pNode != NULL && pNode->data != value ) prevNode = pNode; // point to this node pNode = pNode->next; // move to next node } // did we find it? if (pNode == NULL) return false; // is it the first node? if( pNode == head) head = pNode->next; else // make prevNode point to node after pNode prevNode->next = pNode->next; // in either case, delete the node we found deleteNode( pNode ); // found and removed return true; @Copyright UMBC Training Centers 2012

35 Deleting the ENTIRE Linked List
Delete all nodes, starting at the front While head is not equal to NULL Set a temporary pointer to the first node Set head equal to the first node’s pointer Free the first node’s memory No special code for empty list @Copyright UMBC Training Centers 2012

36 Deleting the Linked List
void deleteList( ) { NODE *pNode; while(head != NULL) { pNode = head; head = head->next; deleteNode(pNode); } void deleteNode( NODE *pNode) free (pNode); @Copyright UMBC Training Centers 2012

37 @Copyright UMBC Training Centers 2012
Exercises Ex3 - 5 @Copyright UMBC Training Centers 2012

38 @Copyright UMBC Training Centers 2012
If you have any comments about this video, please use the contact information in your registration materials to let us know @Copyright UMBC Training Centers 2012


Download ppt "Module 13 Dynamic Memory."

Similar presentations


Ads by Google