1 CS 201 Dynamic Data Structures Debzani Deb. 2 Run time memory layout When a program is loaded into memory, it is organized into four areas of memory.

Slides:



Advertisements
Similar presentations
Linked Lists.
Advertisements

Dynamic memory allocation
Data Structure Lecture-3 Prepared by: Shipra Shukla Assistant Professor Kaziranga University.
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.
CSC 270 – Survey of Programming Languages C Lecture 6 – Pointers and Dynamic Arrays Modified from Dr. Siegfried.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
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.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 7 : September 8.
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:
Informática II Prof. Dr. Gustavo Patiño MJ
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
1 CS 201 Dynamic Data Structures (3) Debzani Deb.
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 CS 201 Dynamic Data Structures (2) Debzani Deb.
1 CS 201 Dynamic Data Structures and Function Pointers Debzani Deb.
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
Chapter 14 Dynamic Data Structures Instructor: Alkar & Demirer.
CSc 352 C : Arrays, Structs, Pointers
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.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Runtime Environments Compiler Construction Chapter 7.
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. This is.
Chapter 14 Dynamic Data Structures Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Lecture 13 Static vs Dynamic Memory Allocation
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.
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.
Lists, Stacks and Queues in C Yang Zhengwei CSCI2100B Data Structures Tutorial 4.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
1 Chapter 16 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion and.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
APS105 Lists. Structures Arrays allow a collection of elements –All of the same type How to collect elements of different types? –Structures; in C: struct.
ECE Application Programming
Pointers *, &, array similarities, functions, sizeof.
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
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.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
CNG 140 C Programming (Lecture set 12) Spring Chapter 13 Dynamic Data Structures.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 5.
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.
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.
Sudeshna Sarkar, CSE, IIT Kharagpur1 Structure and list processing Lecture
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.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R2. Elementary Data Structures.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Linked Lists Source: presentation based on notes written by R.Kay, A. Hill and C.Noble ● Lists in general ● Lists indexed using pointer arrays ● Singly.
Dynamic Allocation Review Structure and list processing
5.13 Recursion Recursive functions Functions that call themselves
Chapter 14: Dynamic Data Structures
Dynamic Memory Allocation
Memory Allocation CS 217.
Linked List.
Dynamic Memory A whole heap of fun….
Pointers, Dynamic Data, and Reference Types
Module 13 Dynamic Memory.
Dynamic Data Structures
Presentation transcript:

1 CS 201 Dynamic Data Structures Debzani Deb

2 Run time memory layout When a program is loaded into memory, it is organized into four areas of memory  Code: The compiled code of the program, including all functions both user-defined and system.  Static data: global variables  Allocated during run time.  Stack:  Contains stack frame that includes local variables, parameters, return address etc.  Function call - push stack frame  Function exit - pop stack frame  Heap:  Dynamic memory – list of free space  Allocated by calloc(), malloc().  Deallocated by free().

3 int x; /* static storage */ void main() { int y; /* stack storage */ char *str; /* stack storage */ str = malloc(100); /* allocates 100 bytes of dynamic heap storage */ y = foo(23); free(str); /* deallocates 100 bytes of dynamic heap storage */ } /* y and str deallocated as stack frame is popped */ int foo(int z) { /* z is stack storage */ char ch[100]; /* ch is stack storage */ if (z == 23) foo(7); return 3; /* z and ch are deallocated as stack frame is popped, 3 put on top of stack */ } Run time memory layout (example)

4 Dynamic memory allocation (1) It is not always known in advance how big an array will be in running program. There are two ways to go around this.  Set aside huge amount of memory when writing the program and hope that it is more than needed.  Allocate the needed memory “on the fly” from the heap. The later is obviously more intelligent and flexible. In order to allocate memory for any built-in or user-defined types, we do the following nump = (int *) malloc (sizeof (int)); planetp = (planet_t *) malloc( sizeof (planet_t));  malloc returns a pointer that points to the start of the allocated memory (or NULL if there is not enough space in the heap).  The pointer returned by malloc has no type (pointer to void) and must be cast to the proper type.

5 Figure 14.4 Dynamic Allocation of Variables for an int, a char, and a Five-Component planet_t Structure

6 Dynamic memory allocation (2) If you need memory to store n array element, each of which is (say) an integer, then you need to do this a = (int *) malloc(total_array_size); where total_array_size = n * sizeof (int)  Alternative calloc (contiguous allocation function) a = (int *) calloc(n, sizeof(int));  calloc initializes the array element to zero, on the other hand malloc provides no initialization.  Both calloc and malloc are declared in.

7 Dynamic memory deallocation Memory allocated by calloc and malloc must be given back explicitly.  free(a) return to the heap the cell whose address is in a.  If a is NULL, there is no effect, if it is the base address of the space allocated by calloc and malloc, the space is deallocated, otherwise there is a system-dependent error.  free(planetp) returns the entire structure pointed to by planetp.  If you do not give the unused memory back, but keep on taking more, you will eat it all and at some point the program will crash.

8 Example a = (int *) malloc( n * sizeof(int)); /* allocate space for n- element array */ if (!a) { printf (“Memory allocation failed !\n”); exit(1); } fill_array (a, n); /* fill the array with numbers */ print_array (a, n); /* print out the array */ printf (“Sum = %d\n”, sum_array (a, n)); free(a); Types must match Always make sure pointer is not Null Always free allocated memory before exiting the program.

9 Pointer to void Pointer must always have a type that they point to. Exception: void * is a generic pointer, and can be assigned to any variable type. However, for good practice, you should always “type cast” it into the appropriate pointer type.  Example: int * p; void * v; If v happens to point to some integer, this is the proper assignment: p = (int *) v; This makes sure that the pointer types agree.

10 Linked list (1) A linked list is a sequence of nodes in which each node but the last contains the address of the next node. An alternative to arrays. Common abstraction to use in programming. data *next a data *next b data *next c data NULL d struct list { int data; struct list *next; } a, b, c, d; a.next = &b; b.next = &c; a.next -> next -> next = &d; /* an alternative c.next = &d; */ d.Next = NULL;

11 Linked list (2) To construct a dynamic linked list, we need to use nodes that have pointer components. Because we may not know how many elements will be in our lists, we can allocate storage for each node as needed and use its pointer component to connect it to the next node. Definition of nodes we are going to use in this lecture typedef struct list_node_s { int digit; struct list_node_s *restp; } list_node_t;  In this definition, struct list_node_s is an alternative name for type list_node_t.

12 Linked list (2) We can allocate and initialize data components of nodes as follows list_node_t *n1_p, *n2_p; n1_p = (list_node_t *) malloc (sizeof(list_node_t)); n1_p -> digit = 5; n2_p = (list_node_t *) malloc (sizeof(list_node_t)); n2_p -> digit = 7; Connecting nodes  Pointer components of above nodes are still undefined. n1_p -> restp = n2_p; copies the address stored in n2_p into the restp component of the node accessed through n1_p. Now they are connected. Accessing digit (7): two ways n2_p -> digit; n1_p -> restp -> digit; End the list n2_p -> restp = NULL; n1_p is the pointer to the first element of the list and is called list head. If we know the address in n1_p, we can access every element of the list. 5 n1_p digit restp 7 n2_p digit restp X 5 n1_p digit ? 7 n2_p digit ? restp

13 Link List Operation (Traversing) Traversing: Processing each node in a linked list in sequence, starting at the list head. Once you understand the following code, try to write a small function that counts the number of elements in a list.

14 Link List Operation (Traversing) Comparison of recursive and iterative list printing

15 Figure Update of Iterative List- Traversing Loop Control Variable

16 Link List Operation (Searching) Find First occurrence of target in the list. 1.What if I put cur_nodep++ instead of cur_nodep -> restp ? Could that work? When? 2.What if the order of the following tests are reversed? (cur_nodep != NULL) && (cur_nodep -> digit != target)

17 Link List Operation (Insertion at Head) Insert at list’s head (i.e. at the front of the list) list_node_t * insertH (list_node_t * headp, int v) { list_node_t *newp; newp = (list_node_t *) malloc(sizeof(list_node_t)); newp->digit = v; newp->restp = headp; return newp; /* return pointer to the new head of the list */ } typedef struct list_node_s { int digit; struct list_node_s *restp; } list_node_t; int main(void){ list_t * pHead = NULL; pHead = insertH(pHead, 3); pHead = insertH(pHead, 5); pHead = insertH(pHead, 7); pHead = insertH(pHead, 9); }

18 Link List Operation (Deletion at Head) After the insertion at last slide, your list now looks like 9 pHead digitrestp 7 digitrestp 5 digitrestp 3 digit X restp list_node_t * deleteH (list_node_t * headp){ list_node_t *newp = headp -> restp; /* newp is now pointing to the 2nd element of the list */ free(headp); return newp; /* return pointer to the new head of the list */ } 7 pHead digitrestp 5 digitrestp 3 digitrestp After the following call pHead = deleteH (pHead);

19 Lists are arrays Quite often the lists are treated as arrays, that can change their size dynamically. data *next a data *next b data *next c data NULL d Assumptions  Indexing of list starts at 0 (as in arrays).  Every index value is unique.  Indices are in growing order (incremented by 1). Index

20 Link List Operation (Deletion at Index) Delete element at some index of the list list_node_t * deleteIndex (list_node_t * headp, int index) { int i; list_node_t * newp, *p, * tmpp; if (index == 0) { // deleting head newp = headp -> restp; free(headp); return newp; }

21 Link List Operation (Deletion at Index) else { // deleting element other than the head for (p = headp, i = 1; (i restp != NULL); i++) /* searching for the element that has a pointer to the one to be deleted */ p = p -> restp; tmpp = p -> restp; /* tmpp now points at the element to be deleted */ if(tmpp != NULL) p -> restp = tmpp -> restp; /* p now points at the element after the one to be deleted */ else /* we are dealing with the last element of the list */ p -> restp = NULL; free(tmpp); return headp; }

22 Important ! Final date has been posted in the website. Remember Exam 2 next Wednesday. Covers  Array  String  Recursion  Structure & Union  Dynamic data storage (upto next Monday) All rules of exam 1 will be applicable.