Page 1 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation Suppose we defined the data type: struct custrec.

Slides:



Advertisements
Similar presentations
Dynamic Allocation and Linked Lists. Dynamic memory allocation in C C uses the functions malloc() and free() to implement dynamic allocation. malloc is.
Advertisements

Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.
Dynamic memory allocation
Chapter 6 Data Types
R4 Dynamically loading processes. Overview R4 is closely related to R3, much of what you have written for R3 applies to R4 In R3, we executed procedures.
Dynamic Memory Allocation (also see pointers lectures) -L. Grewe.
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.
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
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
Introduction of Memory Allocation. Memory Allocation There are two types of memory allocations possible in c. Compile-time or Static allocation Run-time.
Kernighan/Ritchie: Kelley/Pohl:
Dynamic memory allocation. The process of allocating memory at run time is known as dynamic memory allocation. C have four library functions for allocating.
Informática II Prof. Dr. Gustavo Patiño MJ
Dynamic Memory Allocation in C++. Memory Segments in C++ Memory is divided in certain segments – Code Segment Stores application code – Data Segment Holds.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
Linked Lists Chained nodes of information create what are called linked lists, with each node providing a link to the next node. A useful feature of linked.
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
CS3012: Formal Languages and Compilers The Runtime Environment After the analysis phases are complete, the compiler must generate executable code. The.
Outline Midterm results Static variables Memory model
Page 1 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Bits and Bytes How Many bits (or ‘doughnuts’) do we really need? Good question!
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 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Dynamic Memory Allocation 9.8.
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,
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
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.
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.
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.
Chapter 19 Data Structures. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Data Structures A data structure.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Page 1 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft RAM Allocation Chapter 3.
UFS003C3 Lecture 15 Data type in C & C++ Using the STL.
CS 261 – Data Structures C Pointers Review. C is Pass By Value Pass-by-value: a copy of the argument is passed in to a parameter void foo (int a) { a.
1 CSC103: Introduction to Computer and Programming Lecture No 24.
Page 1 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Strings Chapter 5.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
CSC Programming for Science Lecture 34: Dynamic Pointers.
CNG 140 C Programming (Lecture set 12) Spring Chapter 13 Dynamic Data Structures.
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 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.
Pointer Data Type and Pointer Variables III CS1201: Programming Language 2 By: Nouf Aljaffan Edited by : Nouf Almunyif.
CSE 351 Dynamic Memory Allocation 1. Dynamic Memory Dynamic memory is memory that is “requested” at run- time Solves two fundamental dilemmas: How can.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
1 Linked List. 2 List A list refers to a sequence of data items  Example: An array The array index is used for accessing and manipulation of array elements.
What do I need to Know For My Assignment?. C Pointer Review To declare a pointer, we use the * operator. This is similar to but different from using *
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Structured Data Objects (Structs). array Recall our definition of an array: fixedcontiguousall of the same data type an array is a fixed number of contiguous.
Page 1 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Structs Structured Data Objects (Structs) Chapter 7.
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Stack and Heap Memory Stack resident variables include:
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Linked lists.
Circular Buffers, Linked Lists
Linked Lists Chapter 10.
Memory Allocation CS 217.
Linked lists.
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

Page 1 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation Suppose we defined the data type: struct custrec { char ssn[10]; char name[31]; }; char name[31]; }; And then we were to make the declaration: struct custrecrec customer[1000]; (Which requires 41-bytes of contiguous RAM) (Which requires 41 * 1,000 = 41,000 bytes of contiguous RAM) We might get the run-time error message: Not enough memory (Or something similar)

Page 2 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation Well, That’s because there is not enough memory, Right??? Not necessarily. If we were to check, we might find that we actually have 250,000 bytes of ram available. Why Can’t we get the memory we need ?? If we were to look inside RAM, we might see: 401KB: Assigned 401KB: Assigned 36 KB Available 43 KB: Assigned 28 KB: Avail. 78 KB: Assigned 22 KB: Avail. 234 KB: Assigned 29 KB: Available 512 KB: Assigned 35 KB: Avail. 386 KB: Assigned 386 KB: Assigned 31 KB: Avail. 12 KB: Avail. 18 KB: Avail. 26 KB: Avail. 127 KB: Assigned 14 KB: Avail. 23 KB: Assigned 30 KB: Avail. 32 KB: Assigned 76 KB: Assigned

Page 3 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation To get the necessary memory we need NON-CONTIGUOUS storage. Let’s redefine our data type: struct custrec { char ssn[10]; char name[31]; struct custrec * next; }; How can we have a pointer within a structured object ?? struct Remember, when we defined a structured data object (struct), we noted that it could also include a pointer: next The variable (location in RAM) next will contain an address. next If we go that address (assume next contains the address 65100), we will find (on 45-bytes): (Which requires 45-bytes of contiguous RAM) ssn name next Character array on 10-bytes Character array on 31-bytes Address Field on 4-bytes

Page 4 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation How would this work ??? Assume that we wished to keep track of the following records: ssnname ‘ ’ ‘ ’ ‘ ’ ‘ ’ ‘ ’ ‘Chaucer, G.’ ‘Milton, J.’ ‘Browning, R.’ ‘Eliot, T.S.’ ‘Shelley, P.’ But if we were to look at available RAM we saw: Assigned Available Assigned Available Assigned Available Assigned Available

Page 5 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation We know that our structured data object requires: struct custrec { char ssn[10];10-bytes char name[31]; }; 31-bytes 41-bytes 41-bytes of contiguous storage 205-bytes OR: 41 * 5 = 205-bytes of contiguous storage for the database IF we look at our available storage, however: Available Locations Contiguous RAM Available Total Bytes Which is enough for our entire database, and even 1, 2, or 3 records contiguously, BUT NOT ALL 5 RECORDS CONTIGUOUSLY

Page 6 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation Now, let’s redefine our data type as we did before: struct custrec { char ssn[10];10-bytes char name[31];31-bytes struct custrec * next; }; 4-bytes 45 bytes 45 bytes of contiguous storage We could set-up a linked-list to take advantage of our limitations: “ ” “Chaucer, G.” “ ” “Milton, J.” “ ” “Browning R.” “ ” “Eliot, T.S.” “ ” “Shelley, P.” NULL

Page 7 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation NOTE: 1. We still need to allocate 45-contiguous bytes (the size of our record). 2.Records may be allocated contiguously (as with records 3 and 4) but need not be. If contiguous bytes are available, they will be allocated. If not, the next (available) grouping of 45-bytes will be allocated. 3.The space will be Allocated at RUN-TIME; NOT before Does that mean that we must request 45-bytes of contiguous storage 5 times (once for each record) ??? YES ! How do we request the needed memory ?? In C, the necessary statement is: newcust = (struct custrec *) malloc(sizeof(struct custrec)); Assuming that we had previously made the declaration: struct custrec * newcust;

Page 8 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation Command Explanation: struct custrec * newcust; newcust Sets aside 4-bytes of storage at location newcust. newcust = (struct custrec *) malloc(sizeof(struct custrec)); Return the number of bytes we need (in our case: 45) newcust = (struct custrec *) malloc(sizeof(struct custrec)); mallocstdlib.h Function malloc (found in stdlib.h) takes one argument (the number of contiguous bytes of RAM we need) and returns the the address of where those contiguous bytes can be found.

Page 9 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation newcust = (struct custrec *) malloc(sizeof(struct custrec)); REMEMBER REMEMBER: When we refer to an address, we MUST know struct what type of data is stored there (in our case, the data type struct custrec custrec). We need to specify the data type which will be found at that address in advance newcust = (struct custrec *) malloc(sizeof(struct custrec)); Store the address at which 45-bytes of contiguous (where the data struct custrecnewcust type struct custrec can be found) at location (variable) newcust. What if there is NOT enough contiguous RAM available ??

Page 10 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation A good programmer will always check: newcust = (struct custrec *) malloc(sizeof(struct custrec)); if (newcust == NULL) // is there enough memory? { puts("Memory allocation failed - Bye!"); return(0); } return(0); } malloc Function malloc will return the value NULL if the requested amount of contiguous RAM could not be found What about the C code necessary ?? The code that follows assumes that: 1. The database will be entered from the keyboard 2. The User will continue entering records until they enter a RETURN for the customer’s name

Page 11 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation #include struct custrec { char ssn[10], name[31]; struct custrec * next; }; int main() { struct custrec *newcust, *first, *previous, *present; int numrecs = 0; do { newcust = (struct custrec *) malloc(sizeof(struct custrec)); if (newcust == NULL) { puts("memory allocation failed - bye!"); return 0; } if (numrecs == 0) first = newcust; else previous->next = newcust; newcust->next = NULL; numrecs++; printf("Enter Name for customer %d (Return to Quit): ",numrecs); gets(newcust->name); if (strlen(newcust->name)>0) { printf("Enter SSN for customer %s: ",newcust->name); gets(newcust->ssn); } previous = newcust; } while (strlen(newcust->name)>0); return 0; }

Page 12 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation There is one additional feature to dynamically allocated lists: We can free-up memory which we no longer require Assume we had set up our list (as before): “ ” “Chaucer, G.” “ ” “Milton, J.” “ ” “Browning R.” “ ” “Eliot, T.S.” “ ” “Shelley, P.” NULL And we now wished to eliminate Eliot from the list

Page 13 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation How?? The procedure is relatively simple: newcust 1.Get the address of the record to be deleted (assume we store the address in location newcust). 2.Rearrange the pointers: a.If the first record, make the next record the first record b.If the last record, make the previous record the last one c.Otherwise, have the previous record point to the next record newcust 3.Free the address stored (at location newcust). The C command necessary ??? newcust Assuming we have already stored the address to be freed at location newcust, all we need to do is issue the command: free(newcust);

Page 14 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation How is this different than re-arranging the pointers as we did with simple linked lists ?? Unlike our previous examples, the space allocated for the record (in our example, locations 9544 to 9588) are now available for reuse.

Page 15 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation

Page 16 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation

Page 17 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation

Page 18 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation

Page 19 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation

Page 20 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation