Dynamic Data Structures (II)

Size: px
Start display at page:

Download "Dynamic Data Structures (II)"

Transcription

1 Lecture 23 Dynamic Data Structures (II) CptS 121 Summer 2016 Armen Abnousi

2 Data Structure Data structures are different ways of organizing data in computer We design new data structures to make the programs more efficient and also to make programming easier Array is a data structure Helpful to keep a collection of values of the same type It is easy to send them all together to one function Instead of using different names we can access different values only by changing the index Another data structure is linked list

3 Linked List A Linked List is a chain of nodes Each node consists of a data element and a pointer to the next node Each element can be a basic data value, an array or a combination of different values, a struct, etc. While we can have a fixed size linked list, the power of linked lists is in the ability to add/remove nodes dynamically. Data element Link pointer

4 Why Linked Lists? Say we have a sorted list, and we want to add a new element to the list. (a list of students; a new student registers) If we were to use arrays: we needed to find the index appropriate for the new element (i). In the best case, copy the elements in indices i to n, into indices i+1 to n+1 Change the value of element in index i, to the new element. n-i copies (if every element has only one value) Same problem when removing an element Insert 7 in the sorted array 0 i n i i+1 n n

5 Why Linked Lists? Say we have a sorted list, and we want to add a new element to the list. (a list of students; a new student registers) If we use linked lists: We need to create a node for the new element Find the appropriate place for the new node. (i) Set the pointer from the previous node (i-1) to point to the new node. Set the pointer for the new node to point to the node previously in its place No more copying element is involved, only changing two pointers. Insert 9 in the sorted linked list

6 Linked List We need to be able to identify where our list starts and where it ends We will set a pointer to the first node and call it. This pointer variable itself is not dynamically allocated, but the nodes that it refers to will be allocated dynamically We will set the pointer for the last element to NULL, so that we know that s the end of the list. (node*) Data element Link pointer NULL

7 Functions on Linked Lists We can implement multiple functions to work with a linked list: insert(element, ) adds one element to the beginning of the list isinlist(element, ) Traverses over the linked list to see if it contains the element removeelem(element, ) Finds the element in the list and removes its node insertinloc(element, loc, ) inserts the node containing element in the specified location of the list (loc-th node) removenodeloc(loc, ) removes the loc-th node from the list destroylist() removes all nodes from the list printlist() prints all elements of the list

8 Node struct Every node has a component of type node*. typedef struct int element; node_t* next; /* compiler error */ node_t;

9 Node struct Every node has a component of type node*. typedef struct node_t; int element; node_t* next; /* compiler error */ At the time of declaring node_t* component, node_t itself is not completed yet and therefore compiler does know what it is! Instead we can assign a tag to our struct (any name!) and use that tag to let the compiler know what the node_t* is: typedef struct node_t_tag int element; struct node_t_tag* next; node_t; This can be any other data type

10 Linked List Now let s write our main function, where we initialize our. In the beginning there is no node in the list, so the is NULL. By adding new elements we will allocate memory gradually. int main() node_t* = NULL; return 0; At the beginning there is no node in the list.

11 Insert Insert a node in the list: We can add the node to the beginning of the list Make the pointer in the new node to point to the first node in the original list Make the pointer to point to the new node

12 insert Let s update the main to include a call to the function for insert: int main() node_t* = NULL; = insert( 5, ); return 0; Note that we entered element 5 which is an int. Instead we can have any other data type, just by changing the component type for element in the struct Inserts a node containing element 5 in the list and updates the.

13 insert Now we will implement the function insert We want to return the updated node_t* insert(int entry, node_t* ) node_t* node; node = (node_t*)malloc(sizeof(node_t)); if (node!= NULL) return ; node->num = entry; node->next = ; = node; Update the to point to the new node A pointer to node, so that we can allocate dynamic memory for a new node Update the element in new node to be the value we want to insert The new node will point to the first node in the original list. If the list was empty, the pointer will be NULL.

14 Traversing the list - print Print function should go over the list, from node to node, and print the elements stored in it. The traversal starts from the node pointed by and continues until it reaches the node where the pointer to next is NULL NULL Declare a new pointer (node_t*) to do the traversal. node_t* current = ; NULL current Print 9 current = current -> next;

15 Traversing the list - print Print function should go over the list, from node to node, and print the elements stored in it. The traversal starts from the node pointed by and continues until it reaches the node where the pointer to next is NULL NULL Declare a new pointer (node_t*) to do the traversal. node_t* current = ; NULL current Print 6 current = current -> next;

16 Traversing the list - print Root itself is a pointer, Now current is referring to the same node that is pointing to. Print function should go over the list, from node to node, and print the elements stored in it. The traversal starts from the node pointed by and continues until it reaches the node where the pointer to next is NULL. void printlist(int entry, node_t* ) node_t* current; for (current = ; current!= NULL; current = current->next) printf("%d\n", current->num); Because we do not want to lose the, we keep a new pointer to work with, while Keeping the unchanged

17 isinlist This function checks if a given element is stored in any of the nodes in the list and returns a true/false integer. Similar to print function as it traverses the list, but can stop the traversal when it finds the element: use a flag variable done int isinlist(int query, node_t* ) node_t* current; int inlist = 0, done = 0; for (current = ;!done && current!= NULL; current = current->next) if (current->num == query) return inlist; inlist = 1; done = 1; Done is the flag variable to stop the loop when it finds the element, inlist is the return value In addition to checking for the NULL pointer, we check for the done to stop the loop prematurely if we find the query early in list (Note that done and inlist are used similarly in the function, we could replace one by the other)

18 removeelem Given an input element, finds the element in the list and deletes the first node that contains the element from the list: (if there are multiple such nodes only the first one will be deleted) Remove 7

19 removeelem Given an input element, finds the element in the list and deletes the node containing the element from the list: Find the current node (containing the element) Change the pointer from the previous node to point to the next node. Free the current node Remove

20 removeelem node_t* removeelem(int elem, node_t* ) node_t* removed = ; node_t* prev = NULL; int done = 0; for (removed = ;!done && removed!= NULL;) if (removed->num == elem) done = 1; else prev = removed; removed = removed->next; if (done) return ; if (prev!= NULL) prev->next = removed->next; else = removed->next; free(removed); If the elem is found, this will connect prev to the next pointed to by the node that needs to be deleted. If prev is NULL then the node to be Removed is the first node, so we will change the Locates the element in the list: removed refers to the node containing the element and prev, to the node before that. If removed is the first node, prev will be NULL.

21 removeelem node_t* removeelem(int elem, node_t* ) node_t* removed = ; node_t* prev = NULL; int done = 0; for (removed = ;!done && removed!= NULL;) if (removed->num == elem) done = 1; else prev = removed; removed = removed->next; if (done) return ; if (prev!= NULL) prev->next = removed->next; else = removed->next; free(removed); Updating the removed in the if statement inside the loop rather than as the third statement in the for loop, allows us to exit the loop without changing the values for removed or prev. If we had it like: for (remvd=;!done && remvd!=null; remvd=remvd->next) Then in the last iteration where we set done=1, we would still change the removed and then exit the loop, losing the correct node to remove.

22 Pointer to pointer variable In insert and remove functions we returned a node_t* variable (the ). We can use an output parameter for this variable and send a integer status variable as a returned value. For output parameters we have always used pointers. Now, since our variable itself is a pointer, we will need to send/receive a pointer to a pointer.

23 Insert with output node_t* parameter int insert(int entry, node_t** ) node_t* node; int status = 0; node = (node_t*)malloc(sizeof(node_t)); if (node!= NULL) node->num = entry; node->next = *; * = node; status = 1; return status;

24 destroylist Starting from the first node, traverses the list, and as it moves forward, frees the memory for the current node: void destroylist(node_t** ) node_t* current = *; node_t* nextnode; while (current!= NULL) nextnode = current->next; free(current); current = nextnode; * = NULL;

25 Linked List in Memory We declared the as a local variable of type node_t* in main. => it s stored in the stack. main stack NULL heap int main() node_t* = NULL; = insert(5, ); Green font means the program has executed those instructions

26 stack Linked List in Memory Every time we insert a node, we request a malloc: Green font means the program has executed those instructions int main() node_t* = NULL; main insert entry (5) node NULL NULL heap = insert(5, ); node_t* insert(int entry, node_t* ) node_t* node; node = (node_t*)malloc(sizeof(node_t)); if (node!= NULL) return ; node->num = entry; node->next = ; = node;

27 stack Linked List in Memory Every time we insert a node, we request a malloc: Green font means the program has executed those instructions int main() node_t* = NULL; main insert entry (5) node NULL NULL heap num? next? = insert(5, ); node_t* insert(int entry, node_t* ) node_t* node; node = (node_t*)malloc(sizeof(node_t)); if (node!= NULL) return ; node->num = entry; node->next = ; = node;

28 stack Linked List in Memory Every time we insert a node, we request a malloc: Green font means the program has executed those instructions main insert entry (5) node NULL NULL heap 5 NULL int main() node_t* = NULL; = insert(5, ); node_t* insert(int entry, node_t* ) node_t* node; node = (node_t*)malloc(sizeof(node_t)); if (node!= NULL) return ; node->num = entry; node->next = ; = node;

29 stack Linked List in Memory Every time we insert a node, we request a malloc: Green font means the program has executed those instructions main insert entry (5) node NULL heap 5 NULL int main() node_t* = NULL; = insert(5, ); node_t* insert(int entry, node_t* ) node_t* node; node = (node_t*)malloc(sizeof(node_t)); if (node!= NULL) return ; node->num = entry; node->next = ; = node;

30 stack Linked List in Memory Every time we insert a node, we request a malloc: Green font means the program has executed those instructions main Data area for the function Insert is deleted (popped) from the stack as soon as it returns from the function heap 5 NULL int main() node_t* = NULL; = insert(5, ); node_t* insert(int entry, node_t* ) node_t* node; node = (node_t*)malloc(sizeof(node_t)); if (node!= NULL) return ; node->num = entry; node->next = ; = node;

31 stack Linked List in Memory Every time we insert a node, we request a malloc: Green font means the program has executed those instructions heap int main() node_t* = NULL; = insert(5, ); = insert(7, ); main Data area for the function Insert is deleted (popped) from the stack as soon as it returns from the function 7 5 NULL

32 Stack Data Structure Using Linked Lists We have implemented stacks using arrays before Stack can be implemented using linked lists as well If we only allow to insert to or remove from the head of the list (first node), then we have a stack. push(3); push(+); push(5); NULL pop(); + 3 NULL

33 Can you re-write the functions for isinlist, removeelem, destroylist with a recursive viewpoint?

34 Detecting Memory Leaks (optional) for (i = 0; i < 10; i++) ip = malloc(sizeof(int)); This will result in memory leak! In Every iteration one block of memory is allocated and is accessible using the ip pointer. In the next iteration, a new block is allocated and ip is modified, leaving the previous block without a pointer. The blocks allocated in iterations 0 to 8 are not accessible anymore, neither are freed! => memory leak

35 Detecting Memory Leaks (optional) for (i = 0; i < 10; i++) ip = malloc(sizeof(int)); stack heap ip i = 0

36 Detecting Memory Leaks (optional) for (i = 0; i < 10; i++) ip = malloc(sizeof(int)); stack heap ip i = 1 There is no pointer to this block anymore It is unattained but not fred! Memory leak

37 Detecting Memory Leaks (optional) for (i = 0; i < 10; i++) ip = malloc(sizeof(int)); stack heap ip i = 2 There is no pointer to this block anymore It is unattained but not fred! Memory leak

38 Detecting Memory Leaks (optional) Forgetting to free allocated dynamic memory, can result in your computer running out of memory when running your program. The program might stop with runtime error, or your computer might slow down. Specially when memory allocation happens in a loop, you must carefully design the algorithm to make sure every unused block of memory is freed. Make sure every block of memory that is allocated, has at least one pointer to it. (Otherwise, you have some data in the memory but there is no way of accessing it).

39 Detecting Memory Leaks (optional) You can detect memory leaks in Visual Studio using the CRT library: Include/define these in order: #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> Before every exit point of your program enter: _CrtDumpMemoryLeaks(); *return statements in the main and any other exit() command are exit points of your program.

40 Detecting Memory Leaks (optional) Visual Studio #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #include <stdio.h> int main() int* ap; ap = malloc(sizeof(int)); _CrtDumpMemoryLeaks(); return 0; Allocated but not freed

41 Detecting Memory Leaks (optional) Linux systems There are multiple tools that can be used Valgrind is a debugging tool for memory management problems in linux systems One of the facilities valgrind provides is to check for memory leaks Valgrind is probably the best known tool for finding memory leaks

42 Garbage Collection (optional) Some libraries offer garbage collection Garbage collection is a form of automatic memory management Garbage collector looks for allocated memory blocks that don t have any pointer to them (are not used) and deallocates them. This operation happens automatically.

43 Smart Pointers in C++ (optional) A smarter implementation of pointers is called smart pointer. Smart pointers do the deallocation automatically. Smart pointers are available in C++ (and not in C). For a start point, look up smart pointer and/or shared_ptr.

44 References J.R. Hanly & E.B. Koffman, Problem Solving and Program Design in C (8thed.), Pearson, 2016

The combination of pointers, structs, and dynamic memory allocation allow for creation of data structures

The combination of pointers, structs, and dynamic memory allocation allow for creation of data structures Data Structures in C C Programming and Software Tools N.C. State Department of Computer Science Data Structures in C The combination of pointers, structs, and dynamic memory allocation allow for creation

More information

Class Information ANNOUCEMENTS

Class Information ANNOUCEMENTS Class Information ANNOUCEMENTS Third homework due TODAY at 11:59pm. Extension? First project has been posted, due Monday October 23, 11:59pm. Midterm exam: Friday, October 27, in class. Don t forget to

More information

Lecture 14. Arrays II. Selection Sort & Parallel Arrays. CptS 121 Summer 2016 Armen Abnousi

Lecture 14. Arrays II. Selection Sort & Parallel Arrays. CptS 121 Summer 2016 Armen Abnousi Lecture 14 Arrays II Selection Sort & Parallel Arrays CptS 121 Summer 2016 Armen Abnousi Sorting an array We have seen how to search in an array Often we want to sort our arrays for more efficient future

More information

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University (13-2) Dynamic Data Structures I H&K Chapter 13 Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University Dynamic Data Structures (1) Structures that expand and contract

More information

CS61, Fall 2012 Section 2 Notes

CS61, Fall 2012 Section 2 Notes CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors

More information

Run Time Environment

Run Time Environment CS 403 Compiler Construction Lecture 12 Run Time Environment and Management [Based on Chapter 7 of Aho2] 1 Run Time Environment From Lecture 1 to 11, we have seen many jobs that are done by a compiler.

More information

Quiz 0 Review Session. October 13th, 2014

Quiz 0 Review Session. October 13th, 2014 Quiz 0 Review Session October 13th, 2014 Topics (non-exhaustive) Binary. ASCII. Algorithms. Pseudocode. Source code. Compiler. Object code. Scratch. Statements. Boolean expressions. Conditions. Loops.

More information

Manual Allocation. CS 1622: Garbage Collection. Example 1. Memory Leaks. Example 3. Example 2 11/26/2012. Jonathan Misurda

Manual Allocation. CS 1622: Garbage Collection. Example 1. Memory Leaks. Example 3. Example 2 11/26/2012. Jonathan Misurda Manual llocation Dynamic memory allocation is an obvious necessity in a programming environment. S 1622: Garbage ollection Many programming languages expose some functions or keywords to manage runtime

More information

(1-2) Introduction to C Data Structures & Abstract Data Types. Instructor - Andrew S. O Fallon CptS 122 (June 6, 2018) Washington State University

(1-2) Introduction to C Data Structures & Abstract Data Types. Instructor - Andrew S. O Fallon CptS 122 (June 6, 2018) Washington State University (1-2) Introduction to C Data Structures & Abstract Data Types Instructor - Andrew S. O Fallon CptS 122 (June 6, 2018) Washington State University What is a Data Structure? A software construct describing

More information

BBM 201 DATA STRUCTURES

BBM 201 DATA STRUCTURES BBM 201 DATA STRUCTURES Lecture 8: Dynamically Allocated Linked Lists 2017-2018 Fall int x; x = 8; int A[4]; An array is stored as one contiguous block of memory. How can we add a fifth element to the

More information

CS 11 C track: lecture 5

CS 11 C track: lecture 5 CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap Pointers (from last week) Address: location where data stored

More information

Linked-List Basic Examples. A linked-list is Linear collection of self-referential class objects, called nodes Connected by pointer links

Linked-List Basic Examples. A linked-list is Linear collection of self-referential class objects, called nodes Connected by pointer links Linked-List Basic Examples A linked-list is Linear collection of self-referential class objects, called nodes Connected by pointer links Accessed via a pointer to the first node of the list Subsequent

More information

In Java we have the keyword null, which is the value of an uninitialized reference type

In Java we have the keyword null, which is the value of an uninitialized reference type + More on Pointers + Null pointers In Java we have the keyword null, which is the value of an uninitialized reference type In C we sometimes use NULL, but its just a macro for the integer 0 Pointers are

More information

Q1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100

Q1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100 ECE 2035(A) Programming for Hardware/Software Systems Fall 2013 Exam Three November 20 th 2013 Name: Q1: /8 Q2: /30 Q3: /30 Q4: /32 Total: /100 1/10 For functional call related questions, let s assume

More information

Dynamic Data Structures. CSCI 112: Programming in C

Dynamic Data Structures. CSCI 112: Programming in C Dynamic Data Structures CSCI 112: Programming in C 1 It s all about flexibility In the programs we ve made so far, the compiler knows at compile time exactly how much memory to allocate for each variable

More information

Data Structure Series

Data Structure Series Data Structure Series This series is actually something I started back when I was part of the Sweet.Oblivion staff, but then some things happened and I was no longer able to complete it. So now, after

More information

COMP26120: Linked List in C (2018/19) Lucas Cordeiro

COMP26120: Linked List in C (2018/19) Lucas Cordeiro COMP26120: Linked List in C (2018/19) Lucas Cordeiro lucas.cordeiro@manchester.ac.uk Linked List Lucas Cordeiro (Formal Methods Group) lucas.cordeiro@manchester.ac.uk Office: 2.28 Office hours: 10-11 Tuesday,

More information

o Code, executable, and process o Main memory vs. virtual memory

o Code, executable, and process o Main memory vs. virtual memory Goals for Today s Lecture Memory Allocation Prof. David August COS 217 Behind the scenes of running a program o Code, executable, and process o Main memory vs. virtual memory Memory layout for UNIX processes,

More information

CS 241 Data Organization Binary Trees

CS 241 Data Organization Binary Trees CS 241 Data Organization Binary Trees Brooke Chenoweth University of New Mexico Fall 2017 Binary Tree: Kernighan and Ritchie 6.5 Read a file and count the occurrences of each word. now is the time for

More information

Cpt S 122 Data Structures. Data Structures

Cpt S 122 Data Structures. Data Structures Cpt S 122 Data Structures Data Structures Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Introduction Self Referential Structures Dynamic Memory Allocation

More information

Cpt S 122 Data Structures. Course Review Midterm Exam # 1

Cpt S 122 Data Structures. Course Review Midterm Exam # 1 Cpt S 122 Data Structures Course Review Midterm Exam # 1 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 1 When: Friday (09/28) 12:10-1pm Where:

More information

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS Pages 792 to 800 Anna Rakitianskaia, University of Pretoria INITIALISING POINTER VARIABLES Pointer variables are declared by putting

More information

CP2 Revision. theme: dynamic datatypes & data structures

CP2 Revision. theme: dynamic datatypes & data structures CP2 Revision theme: dynamic datatypes & data structures structs can hold any combination of datatypes handled as single entity struct { }; ;

More information

CSC 1600 Memory Layout for Unix Processes"

CSC 1600 Memory Layout for Unix Processes CSC 16 Memory Layout for Unix Processes" 1 Lecture Goals" Behind the scenes of running a program" Code, executable, and process" Memory layout for UNIX processes, and relationship to C" : code and constant

More information

ECE 2035 Programming HW/SW Systems Fall problems, 5 pages Exam Three 28 November 2012

ECE 2035 Programming HW/SW Systems Fall problems, 5 pages Exam Three 28 November 2012 Instructions: This is a closed book, closed note exam. Calculators are not permitted. If you have a question, raise your hand and I will come to you. Please work the exam in pencil and do not separate

More information

Programs in memory. The layout of memory is roughly:

Programs in memory. The layout of memory is roughly: Memory 1 Programs in memory 2 The layout of memory is roughly: Virtual memory means that memory is allocated in pages or segments, accessed as if adjacent - the platform looks after this, so your program

More information

ECE264 Spring 2013 Final Exam, April 30, 2013

ECE264 Spring 2013 Final Exam, April 30, 2013 ECE264 Spring 2013 Final Exam, April 30, 2013 In signing this statement, I hereby certify that the work on this exam is my own and that I have not copied the work of any other student while completing

More information

Dynamic Memory Management. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Dynamic Memory Management. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island Dynamic Memory Management Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island 1 Dynamic Memory Allocation Dynamic memory allocation is used to

More information

Lecture 8 Dynamic Memory Allocation

Lecture 8 Dynamic Memory Allocation Lecture 8 Dynamic Memory Allocation CS240 1 Memory Computer programs manipulate an abstraction of the computer s memory subsystem Memory: on the hardware side 3 @ http://computer.howstuffworks.com/computer-memory.htm/printable

More information

unsigned char memory[] STACK ¼ 0x xC of address space globals function KERNEL code local variables

unsigned char memory[] STACK ¼ 0x xC of address space globals function KERNEL code local variables Graded assignment 0 will be handed out in section Assignment 1 Not that bad Check your work (run it through the compiler) Factorial Program Prints out ENTERING, LEAVING, and other pointers unsigned char

More information

Lecture 7: Data Structures. EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

Lecture 7: Data Structures. EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology Lecture 7: Data Structures 1 Introduction: dynamic array Conventional array in C has fix number of elements Dynamic array is array with variable number of elements: actually a pointer and a variable indicating

More information

Repetition Structures II

Repetition Structures II Lecture 9 Repetition Structures II For and do-while loops CptS 121 Summer 2016 Armen Abnousi Types of Control Structures Sequential All programs that we have written so far The statements inside a pair

More information

(3-2) Basics of a Stack. Instructor - Andrew S. O Fallon CptS 122 (January 26, 2018) Washington State University

(3-2) Basics of a Stack. Instructor - Andrew S. O Fallon CptS 122 (January 26, 2018) Washington State University (3-2) Basics of a Stack Instructor - Andrew S. O Fallon CptS 122 (January 26, 2018) Washington State University What is a Stack? A finite sequence of nodes, where only the top node may be accessed Insertions

More information

https://lambda.mines.edu A pointer is a value that indicates location in memory. When we change the location the pointer points to, we say we assign the pointer a value. When we look at the data the pointer

More information

Run-time Environments - 3

Run-time Environments - 3 Run-time Environments - 3 Y.N. Srikant Computer Science and Automation Indian Institute of Science Bangalore 560 012 NPTEL Course on Principles of Compiler Design Outline of the Lecture n What is run-time

More information

Lecture 5. Functions II. Functions with Arguments. CptS 121 Summer 2016 Armen Abnousi

Lecture 5. Functions II. Functions with Arguments. CptS 121 Summer 2016 Armen Abnousi Lecture 5 Functions II Functions with Arguments CptS 121 Summer 2016 Armen Abnousi Remember Functions break problems into smaller pieces Easier to read, test and maintain Functions allow to avoid repetition

More information

Data Structures in C. C Programming and Software Tools. N.C. State Department of Computer Science

Data Structures in C. C Programming and Software Tools. N.C. State Department of Computer Science Data Structures in C C Programming and Software Tools N.C. State Department of Computer Science Data Structures in C The combination of pointers, structs, and dynamic memory allocation allows for creation

More information

Solution for Data Structure

Solution for Data Structure Solution for Data Structure May 2016 INDEX Q1 a 2-3 b 4 c. 4-6 d 7 Q2- a 8-12 b 12-14 Q3 a 15-18 b 18-22 Q4- a 22-35 B..N.A Q5 a 36-38 b N.A Q6- a 39-42 b 43 1 www.brainheaters.in Q1) Ans: (a) Define ADT

More information

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING APS 105 Computer Fundamentals Final Examination December 14, 2012 2:00 p.m. 4:30 p.m. (150 minutes) Examiners: J. Anderson, B. Li, M. Sadoghi,

More information

Compilers. 8. Run-time Support. Laszlo Böszörmenyi Compilers Run-time - 1

Compilers. 8. Run-time Support. Laszlo Böszörmenyi Compilers Run-time - 1 Compilers 8. Run-time Support Laszlo Böszörmenyi Compilers Run-time - 1 Run-Time Environment A compiler needs an abstract model of the runtime environment of the compiled code It must generate code for

More information

DAY 3. CS3600, Northeastern University. Alan Mislove

DAY 3. CS3600, Northeastern University. Alan Mislove C BOOTCAMP DAY 3 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh and Pascal Meunier s course at Purdue Memory management 2 Memory management Two

More information

Memory Allocation. Static Allocation. Dynamic Allocation. Dynamic Storage Allocation. CS 414: Operating Systems Spring 2008

Memory Allocation. Static Allocation. Dynamic Allocation. Dynamic Storage Allocation. CS 414: Operating Systems Spring 2008 Dynamic Storage Allocation CS 44: Operating Systems Spring 2 Memory Allocation Static Allocation (fixed in size) Sometimes we create data structures that are fixed and don t need to grow or shrink. Dynamic

More information

CS 11 C track: lecture 6

CS 11 C track: lecture 6 CS 11 C track: lecture 6 Last week: pointer arithmetic This week: The gdb program struct typedef linked lists gdb for debugging (1) gdb: the Gnu DeBugger http://courses.cms.caltech.edu/cs11/material /c/mike/misc/gdb.html

More information

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions? Lecture 14 No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions? Friday, February 11 CS 215 Fundamentals of Programming II - Lecture 14 1 Outline Static

More information

CSCI-UA /2. Computer Systems Organization Lecture 19: Dynamic Memory Allocation: Basics

CSCI-UA /2. Computer Systems Organization Lecture 19: Dynamic Memory Allocation: Basics Slides adapted (and slightly modified) from: Clark Barrett Jinyang Li Randy Bryant Dave O Hallaron CSCI-UA.0201-001/2 Computer Systems Organization Lecture 19: Dynamic Memory Allocation: Basics Mohamed

More information

EECE.2160: ECE Application Programming

EECE.2160: ECE Application Programming Fall 2017 Programming Assignment #10: Doubly-Linked Lists Due Monday, 12/18/17, 11:59:59 PM (Extra credit ( 5 pts on final average), no late submissions or resubmissions) 1. Introduction This assignment

More information

Programming in C. Lecture 5: Aliasing, Graphs, and Deallocation. Dr Neel Krishnaswami. Michaelmas Term University of Cambridge

Programming in C. Lecture 5: Aliasing, Graphs, and Deallocation. Dr Neel Krishnaswami. Michaelmas Term University of Cambridge Programming in C Lecture 5: Aliasing, Graphs, and Deallocation Dr Neel Krishnaswami University of Cambridge Michaelmas Term 2017-2018 1 / 20 The C API for Dynamic Memory Allocation void *malloc(size_t

More information

CSCI 2132 Software Development. Lecture 29: Dynamic Memory Allocation

CSCI 2132 Software Development. Lecture 29: Dynamic Memory Allocation CSCI 2132 Software Development Lecture 29: Dynamic Memory Allocation Instructor: Vlado Keselj Faculty of Computer Science Dalhousie University 22-Nov-2017 (29) CSCI 2132 1 Previous Lecture Protecting header

More information

(6-1) Basics of a Queue. Instructor - Andrew S. O Fallon CptS 122 (September 26, 2018) Washington State University

(6-1) Basics of a Queue. Instructor - Andrew S. O Fallon CptS 122 (September 26, 2018) Washington State University (6-1) Basics of a Queue Instructor - Andrew S. O Fallon CptS 122 (September 26, 2018) Washington State University What is a Queue? 2 A linear data structure with a finite sequence of nodes, where nodes

More information

Lists (Section 5) Lists, linked lists Implementation of lists in C Other list structures List implementation of stacks, queues, priority queues

Lists (Section 5) Lists, linked lists Implementation of lists in C Other list structures List implementation of stacks, queues, priority queues (Section 5) Lists, linked lists Implementation of lists in C Other list structures List implementation of stacks, queues, priority queues By: Pramod Parajuli, Department of Computer Science, St. Xavier

More information

CS61C Midterm Review on C & Memory Management

CS61C Midterm Review on C & Memory Management CS61C Midterm Review on C & Memory Management Fall 2006 Aaron Staley Some material taken from slides by: Michael Le Navtej Sadhal Overview C Array and Pointer Goodness! Memory Management The Three Three

More information

C PROGRAMMING Lecture 5. 1st semester

C PROGRAMMING Lecture 5. 1st semester C PROGRAMMING Lecture 5 1st semester 2017-2018 Program Address Space The Stack The stack is the place where all local variables are stored a local variable is declared in some scope Example int x; //creates

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 2 Thomas Wies New York University Review Last week Programming Languages Overview Syntax and Semantics Grammars and Regular Expressions High-level

More information

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 4/18/2013

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 4/18/2013 Linear Structure Linear Structures Chapter 4 CPTR 318 Every non-empty linear structure has A unique element called first A unique element called last Every element except last has a unique successor Every

More information

Memory Management. CSC215 Lecture

Memory Management. CSC215 Lecture Memory Management CSC215 Lecture Outline Static vs Dynamic Allocation Dynamic allocation functions malloc, realloc, calloc, free Implementation Common errors Static Allocation Allocation of memory at compile-time

More information

15. Stacks and Queues

15. Stacks and Queues COMP1917 15s2 15. Stacks and Queues 1 COMP1917: Computing 1 15. Stacks and Queues Reading: Moffat, Section 10.1-10.2 Overview Stacks Queues Adding to the Tail of a List Efficiency Issues Queue Structure

More information

Compiler construction 2009

Compiler construction 2009 Compiler construction 2009 Lecture 6 Some project extensions. Pointers and heap allocation. Object-oriented languages. Module systems. Memory structure Javalette restrictions Only local variables and parameters

More information

CS 314 Principles of Programming Languages. Lecture 11

CS 314 Principles of Programming Languages. Lecture 11 CS 314 Principles of Programming Languages Lecture 11 Zheng Zhang Department of Computer Science Rutgers University Wednesday 12 th October, 2016 Zheng Zhang 1 eddy.zhengzhang@cs.rutgers.edu Class Information

More information

CA341 - Comparative Programming Languages

CA341 - Comparative Programming Languages CA341 - Comparative Programming Languages David Sinclair Dynamic Data Structures Generally we do not know how much data a program will have to process. There are 2 ways to handle this: Create a fixed data

More information

Memory Management. CS31 Pascal Van Hentenryck CS031. Lecture 19 1

Memory Management. CS31 Pascal Van Hentenryck CS031. Lecture 19 1 Memory Management CS31 Pascal Van Hentenryck CS031 Lecture 19 1 Memory Management What is it? high-level languages abstract many aspects of memory management Support varies with the language Java (ML/Prolog/Lisp/Smalltalk)

More information

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Chapter 2 (Dynamic variable (i.e. pointer), Static variable) Chapter 2 (Dynamic variable (i.e. pointer), Static variable) August_04 A2. Identify and explain the error in the program below. [4] #include int *pptr; void fun1() { int num; num=25; pptr= &num;

More information

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive) Final Exam Exercises Chapters 1-7 + 11 Write C++ code to: l Determine if a number is odd or even CS 2308 Fall 2016 Jill Seaman l Determine if a number/character is in a range - 1 to 10 (inclusive) - between

More information

Low-Level C Programming. Memory map Pointers Arrays Structures

Low-Level C Programming. Memory map Pointers Arrays Structures Low-Level C Programming Memory map Pointers Arrays Structures Memory Map 0x7FFF_FFFF Binaries load at 0x20000 by default Stack start set by binary when started Stack grows downwards You will need one stack

More information

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013 Linear Structure Linear Structures Chapter 4 CPTR 318 Every non-empty linear structure has A unique element called first A unique element called last Every element except last has a unique successor Every

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 11: Structures and Memory (yaseminb@kth.se) Overview Overview Lecture 11: Structures and Memory Structures Continued Memory Allocation Lecture 11: Structures and Memory Structures Continued Memory

More information

6.S096: Introduction to C/C++

6.S096: Introduction to C/C++ 6.S096: Introduction to C/C++ Frank Li, Tom Lieber, Kyle Murray Lecture 4: Data Structures and Debugging! January 17, 2012 Today Memory Leaks and Valgrind Tool Structs and Unions Opaque Types Enum and

More information

Lecture Notes on Memory Management

Lecture Notes on Memory Management Lecture Notes on Memory Management 15-122: Principles of Imperative Computation Frank Pfenning Lecture 22 November 11, 2010 1 Introduction Unlike C0 and other modern languages like Java, C#, or ML, C requires

More information

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018 CS 31: Intro to Systems Pointers and Memory Kevin Webb Swarthmore College October 2, 2018 Overview How to reference the location of a variable in memory Where variables are placed in memory How to make

More information

(2-1) Data Structures & The Basics of a Linked List I. Instructor - Andrew S. O Fallon CptS 122 (August 27, 2018) Washington State University

(2-1) Data Structures & The Basics of a Linked List I. Instructor - Andrew S. O Fallon CptS 122 (August 27, 2018) Washington State University (2-1) Data Structures & The Basics of a Linked List I Instructor - Andrew S. O Fallon CptS 122 (August 27, 2018) Washington State University How do we Select a Data Structure? (1) Select a data structure

More information

Selection Structures II

Selection Structures II Lecture 7 Selection Structures II Nested if and switch statements CptS 121 Summer 2016 Armen Abnousi If () if() Nested if statements An if- statement can be placed inside another if- statement. Every matches

More information

Structure of Programming Languages Lecture 10

Structure of Programming Languages Lecture 10 Structure of Programming Languages Lecture 10 CS 6636 4536 Spring 2017 CS 6636 4536 Lecture 10: Classes... 1/23 Spring 2017 1 / 23 Outline 1 1. Types Type Coercion and Conversion Type Classes, Generics,

More information

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline CS 0 Lecture 8 Chapter 5 Louden Outline The symbol table Static scoping vs dynamic scoping Symbol table Dictionary associates names to attributes In general: hash tables, tree and lists (assignment ) can

More information

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12 Week 9 Part 1 Kyle Dewey Overview Dynamic allocation continued Heap versus stack Memory-related bugs Exam #2 Dynamic Allocation Recall... Dynamic memory allocation allows us to request memory on the fly

More information

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 16, SPRING 2013 TOPICS TODAY Project 6 Perils & Pitfalls of Memory Allocation C Function Call Conventions in Assembly Language PERILS

More information

Memory Allocation in C C Programming and Software Tools. N.C. State Department of Computer Science

Memory Allocation in C C Programming and Software Tools. N.C. State Department of Computer Science Memory Allocation in C C Programming and Software Tools N.C. State Department of Computer Science The Easy Way Java (JVM) automatically allocates and reclaims memory for you, e.g... Removed object is implicitly

More information

CS61C : Machine Structures

CS61C : Machine Structures inst.eecs.berkeley.edu/~cs61c/su06 CS61C : Machine Structures Lecture #6: Memory Management CS 61C L06 Memory Management (1) 2006-07-05 Andy Carle Memory Management (1/2) Variable declaration allocates

More information

Memory management. Johan Montelius KTH

Memory management. Johan Montelius KTH Memory management Johan Montelius KTH 2017 1 / 22 C program # include int global = 42; int main ( int argc, char * argv []) { if( argc < 2) return -1; int n = atoi ( argv [1]); int on_stack

More information

ECE 2400 Computer Systems Programming, Fall 2018 PA2: List and Vector Data Structures

ECE 2400 Computer Systems Programming, Fall 2018 PA2: List and Vector Data Structures School of Electrical and Computer Engineering Cornell University revision: 2018-09-25-13-37 1. Introduction The second programming assignment is designed to give you experience working with two important

More information

Linked data structures. EECS 211 Winter 2019

Linked data structures. EECS 211 Winter 2019 Linked data structures EECS 211 Winter 2019 2 Initial code setup $ cd eecs211 $ curl $URL211/lec/07linked.tgz tar zx $ cd 07linked Preliminaries 3 4 Two views on malloc and free The client/c view: malloc(n)

More information

COSC Software Engineering. Lecture 16: Managing Memory Managers

COSC Software Engineering. Lecture 16: Managing Memory Managers COSC345 2013 Software Engineering Lecture 16: Managing Memory Managers Outline Typical problems (from previous lectures) Memory leaks aren t just for (Objective) C Tracking malloc() calls Catching calls

More information

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016 CS 31: Intro to Systems Pointers and Memory Martin Gagne Swarthmore College February 16, 2016 So we declared a pointer How do we make it point to something? 1. Assign it the address of an existing variable

More information

CIS 190: C/C++ Programming. Linked Lists

CIS 190: C/C++ Programming. Linked Lists CIS 190: C/C++ Programming Linked Lists Why Use Linked Lists? solve many of the problems arrays have like Problems with Arrays arrays have a fixed size may be too large, or too small arrays must be held

More information

ECE 2400 Computer Systems Programming Fall 2017 Topic 7: C Lists and Vectors

ECE 2400 Computer Systems Programming Fall 2017 Topic 7: C Lists and Vectors ECE 2400 Computer Systems Programming Fall 2017 Topic 7: C Lists and Vectors School of Electrical and Computer Engineering Cornell University revision: 2017-09-29-08-04 1 Lists 2 1.1. List Interface................................

More information

COP 3502 Section 2 Exam #2 Version A Spring /23/2017

COP 3502 Section 2 Exam #2 Version A Spring /23/2017 COP 3502 Section 2 Exam #2 Version A Spring 2017 3/23/2017 Lecturer: Arup Guha Directions: Answer all multiple choice questions on the scantron. Each question has a single correct answer. In case of ambiguities,

More information

ENEE 150: Intermediate Programming Concepts for Engineers Spring 2018 Handout #27. Midterm #2 Review

ENEE 150: Intermediate Programming Concepts for Engineers Spring 2018 Handout #27. Midterm #2 Review ENEE 150: Intermediate Programming Concepts for Engineers Spring 2018 Handout #27 Midterm #2 Review 1 Time and Location The midterm will be given in class during normal class hours, 11:00a.m.-12:15p.m.,

More information

CSE 333 Midterm Exam Sample Solution 7/28/14

CSE 333 Midterm Exam Sample Solution 7/28/14 Question 1. (20 points) C programming. For this question implement a C function contains that returns 1 (true) if a given C string appears as a substring of another C string starting at a given position.

More information

1 Dynamic Memory continued: Memory Leaks

1 Dynamic Memory continued: Memory Leaks CS104: Data Structures and Object-Oriented Design (Fall 2013) September 3, 2013: Dynamic Memory, continued; A Refresher on Recursion Scribes: CS 104 Teaching Team Lecture Summary In this lecture, we continue

More information

Singly linked lists in C.

Singly linked lists in C. Singly linked lists in C http://www.cprogramming.com/tutorial/c/lesson15.html By Alex Allain Linked lists are a way to store data with structures so that the programmer can automatically create a new place

More information

Last week. Data on the stack is allocated automatically when we do a function call, and removed when we return

Last week. Data on the stack is allocated automatically when we do a function call, and removed when we return Last week Data can be allocated on the stack or on the heap (aka dynamic memory) Data on the stack is allocated automatically when we do a function call, and removed when we return f() {... int table[len];...

More information

Lecture 10 Notes Linked Lists

Lecture 10 Notes Linked Lists Lecture 10 Notes Linked Lists 15-122: Principles of Imperative Computation (Summer 1 2015) Frank Pfenning, Rob Simmons, André Platzer 1 Introduction In this lecture we discuss the use of linked lists to

More information

Data Structures and Algorithms (DSA) Course 5 Lists. Iulian Năstac

Data Structures and Algorithms (DSA) Course 5 Lists. Iulian Năstac Data Structures and Algorithms (DSA) Course 5 Lists Iulian Năstac Cap. Lists (recapitulation) 1. Introduction Linked lists are the best and simplest example of a dynamic data structure that uses pointers

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

C Structures & Dynamic Memory Management

C Structures & Dynamic Memory Management C Structures & Dynamic Memory Management Goals of this Lecture Help you learn about: Structures and unions Dynamic memory management Note: Will be covered in precepts as well We look at them in more detail

More information

CMSC 341 Lecture 2 Dynamic Memory and Pointers

CMSC 341 Lecture 2 Dynamic Memory and Pointers CMSC 341 Lecture 2 Dynamic Memory and Pointers Park Sects. 01 & 02 Based on earlier course slides at UMBC Today s Topics Stack vs Heap Allocating and freeing memory new and delete Memory Leaks Valgrind

More information

ECE264 Fall 2013 Exam 3, November 20, 2013

ECE264 Fall 2013 Exam 3, November 20, 2013 ECE264 Fall 2013 Exam 3, November 20, 2013 In signing this statement, I hereby certify that the work on this exam is my own and that I have not copied the work of any other student while completing it.

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Memory Management. Didactic Module 14 Programming Languages - EEL670 1

Memory Management. Didactic Module 14 Programming Languages - EEL670 1 Memory Management Didactic Module 14 Programming Languages - EEL670 1 Dynamic Memory Allocation Lots of things need memory at runtime: Activation records Objects Explicit allocations: new, malloc, etc.

More information

Memory Management. Chapter Fourteen Modern Programming Languages, 2nd ed. 1

Memory Management. Chapter Fourteen Modern Programming Languages, 2nd ed. 1 Memory Management Chapter Fourteen Modern Programming Languages, 2nd ed. 1 Dynamic Memory Allocation Lots of things need memory at runtime: Activation records Objects Explicit allocations: new, malloc,

More information

HOT-Compilation: Garbage Collection

HOT-Compilation: Garbage Collection HOT-Compilation: Garbage Collection TA: Akiva Leffert aleffert@andrew.cmu.edu Out: Saturday, December 9th In: Tuesday, December 9th (Before midnight) Introduction It s time to take a step back and congratulate

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information