Module 13 Dynamic Memory.

Slides:



Advertisements
Similar presentations
Pointers.
Advertisements

Stacks, Queues, and Linked Lists
Linked Lists.
Linked Lists CSE 2451 Matt Boggus. Dynamic memory reminder Allocate memory during run-time malloc() and calloc() – return a void pointer to memory or.
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.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Module R2 CS450. Next Week R1 is due next Friday ▫Bring manuals in a binder - make sure to have a cover page with group number, module, and date. You.
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
1 Memory Allocation Professor Jennifer Rexford COS 217.
Agenda  Review: pointer & array  Relationship between pointer & array  Dynamic memory allocation.
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.
DYNAMIC MEMORY MANAGEMENT. int x; When the source code containing this statement is compiled and linked, an executable file is generated. When the executable.
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:
Programming III SPRING 2015 School of Computer and Information Sciences Francisco R. Ortega, Ph.D. McKnight Fellow and GAANN Fellow LECTURE #5 More about.
Informática II Prof. Dr. Gustavo Patiño MJ
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Pointers Applications
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
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.
Programming in C Advanced Pointers. Pointers to Pointers Since a pointer is a variable type, a pointer may point to another pointer.Since a pointer is.
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.
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.
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.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using 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.
ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory. Dynamic vs Static Allocation Dynamic  On the heap  Amount of memory chosen at runtime  Can change allocated.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Programming in C Advanced Pointers.
CSE 220 – C Programming malloc, calloc, realloc.
Dynamic Allocation in C
Stack and Heap Memory Stack resident variables include:
Dynamic Allocation Review Structure and list processing
5.13 Recursion Recursive functions Functions that call themselves
Lectures linked lists Chapter 6 of textbook
UNIT-3 LINKED LIST.
Arrays & Dynamic Memory Allocation
Programmazione I a.a. 2017/2018.
Prof. Neary Adapted from slides by Dr. Katherine Gibson
CS157: Dynamic Memory Dynamic Memory 11/9/201804/25/06.
Programming and Data Structures
Pointers, Dynamic Data, and Reference Types
CSC215 Lecture Memory Management.
Dynamic Memory Allocation
Dynamic Memory Allocation
Memory Allocation CS 217.
Dynamic Memory Allocation
EECE.2160 ECE Application Programming
Review & Lab assignments
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
Dynamic Memory A whole heap of fun….
Linked List.
CS111 Computer Programming
EENG212 – Algorithms & Data Structures Fall 07/08 – Lecture Notes # 5b
Linked Lists Adapted from Dr. Mary Eberlein, UT Austin.
Dynamic Memory A whole heap of fun….
Chapter 10-1: Dynamic Memory Allocation
DYNAMIC MEMORY MANAGEMENT
Programming in C Advanced Pointers.
Dynamic Memory – A Review
Pointers, Dynamic Data, and Reference Types
Dynamic Data Structures
Presentation transcript:

Module 13 Dynamic Memory

@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 www.umbctraining.com @Copyright UMBC Training Centers 2012

@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. www.umbctraining.com @Copyright UMBC Training Centers 2012

@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 www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Sizeof at Work C::B sizeOf www.umbctraining.com @Copyright UMBC Training Centers 2012

@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 www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Malloc in use From http://www.cplusplus.com/reference/cstdlib/malloc/ www.umbctraining.com @Copyright UMBC Training Centers 2012

@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 www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Calloc() in use http://www.cplusplus.com/reference/cstdlib/calloc/ www.umbctraining.com @Copyright UMBC Training Centers 2012

@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)); www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Realloc() in use http://www.cplusplus.com/reference/cstdlib/realloc/ www.umbctraining.com @Copyright UMBC Training Centers 2012

@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); } www.umbctraining.com @Copyright UMBC Training Centers 2012

@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); www.umbctraining.com @Copyright UMBC Training Centers 2012

@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; www.umbctraining.com @Copyright UMBC Training Centers 2012

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

@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 www.umbctraining.com @Copyright UMBC Training Centers 2012

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]; } www.umbctraining.com @Copyright UMBC Training Centers 2012

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

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); www.umbctraining.com @Copyright UMBC Training Centers 2012

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

@Copyright UMBC Training Centers 2012 Exercises Ex1 www.umbctraining.com @Copyright UMBC Training Centers 2012

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

@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; www.umbctraining.com @Copyright UMBC Training Centers 2012

@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 www.umbctraining.com @Copyright UMBC Training Centers 2012

@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; www.umbctraining.com @Copyright UMBC Training Centers 2012

@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 www.umbctraining.com @Copyright UMBC Training Centers 2012

@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; } www.umbctraining.com @Copyright UMBC Training Centers 2012

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 } www.umbctraining.com @Copyright UMBC Training Centers 2012

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; } www.umbctraining.com @Copyright UMBC Training Centers 2012

@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 www.umbctraining.com @Copyright UMBC Training Centers 2012

@Copyright UMBC Training Centers 2012 Finding an item www.umbctraining.com @Copyright UMBC Training Centers 2012

@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; } www.umbctraining.com @Copyright UMBC Training Centers 2012

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 www.umbctraining.com @Copyright UMBC Training Centers 2012

@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; www.umbctraining.com @Copyright UMBC Training Centers 2012

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 www.umbctraining.com @Copyright UMBC Training Centers 2012

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

@Copyright UMBC Training Centers 2012 Exercises Ex3 - 5 www.umbctraining.com @Copyright UMBC Training Centers 2012

@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 www.umbctraining.com @Copyright UMBC Training Centers 2012