CS 237 Meeting 19 10/24/12

Similar documents
CS 237 Meeting 18 10/22/12

CS61, Fall 2012 Section 2 Notes

Binary Search Tree 1.0. Generated by Doxygen Mon Jun :12:39

Kurt Schmidt. October 30, 2018

Dynamic Data Structures. CSCI 112: Programming in C

CS 241 Data Organization Binary Trees

ECE264 Fall 2013 Exam 3, November 20, 2013

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

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

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

ECE264 Spring 2013 Final Exam, April 30, 2013

Recursion, Trees and Tree Traversal. Module CE System Programming & Computer Control Systems

Motivation was to facilitate development of systems software, especially OS development.

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

CA341 - Comparative Programming Languages

Heap Arrays and Linked Lists. Steven R. Bagley

CSCI 171 Chapter Outlines

Singly linked lists in C.

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

CS 610: Intermediate Programming: C/C++ Making Programs General An Introduction to Linked Lists

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

CSE 333 Midterm Exam 2/14/14

CS 11 C track: lecture 5

Linked Lists. .. and other linked structures. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

ch = argv[i][++j]; /* why does ++j but j++ does not? */

Search Trees. Data and File Structures Laboratory. DFS Lab (ISI) Search Trees 1 / 17

Introduction to Linked Lists

Quiz 0 Answer Key. Answers other than the below may be possible. Multiple Choice. 0. a 1. a 2. b 3. c 4. b 5. d. True or False.

Intermediate Programming, Spring 2017*

Dynamic memory allocation (malloc)

Computer Science 322 Operating Systems Mount Holyoke College Spring Topic Notes: C and Unix Overview

Final CSE 131B Spring 2004

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

CS 231 Data Structures and Algorithms, Fall 2016

MIDTERM EXAM. CS 217 October 28, Name: Precept: Honor Code: Score: Problem Score Max

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

CSE 333 Midterm Exam Sample Solution 7/29/13

211: Computer Architecture Summer 2016

CSE 333 Midterm Exam 7/29/13

When you add a number to a pointer, that number is added, but first it is multiplied by the sizeof the type the pointer points to.

Run Time Environment

Dynamic memory allocation

Structures. Basics of Structures (6.1) EECS l Now struct point is a valid type. l Defining struct variables: struct point { int x; int y; };

Compiling and Running a C Program in Unix

CP2 Revision. theme: dynamic datatypes & data structures

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.

Class Information ANNOUCEMENTS

CS349/SE382 A1 C Programming Tutorial

C Data Structures Stacks. Stack. push Adds a new node to the top of the stack

THE UNIVERSITY OF WESTERN ONTARIO. COMPUTER SCIENCE 211a FINAL EXAMINATION 17 DECEMBER HOURS

CS 261 Data Structures. Introduction to C Programming

Short Notes of CS201

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

CS3157: Advanced Programming. Outline

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

CS Programming In C

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

CS201 - Introduction to Programming Glossary By

Recitation 2/18/2012

Week 5, continued. This is CS50. Harvard University. Fall Cheng Gong

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz

BBM 201 DATA STRUCTURES

An Introduction to C++

Motivation was to facilitate development of systems software, especially OS development.

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

[0569] p 0318 garbage

Arrays and Pointers. CSE 2031 Fall November 11, 2013

A brief introduction to C programming for Java programmers

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

Linked Data Representations

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

CS24 Week 2 Lecture 1

CS-220 Spring 2018 Test 1 Version A Feb. 28, Name:

CS113: Lecture 4. Topics: Functions. Function Activation Records

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

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Procedural programming with C

Exercise Session 2 Simon Gerber

C & Data Structures syllabus

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017

Problem 2 Add the two 2 s complement signed 8-bit values given below, and express your answer in decimal.

Programs in memory. The layout of memory is roughly:

ECE 15B COMPUTER ORGANIZATION

Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: C and Unix Overview

printf( Please enter another number: ); scanf( %d, &num2);

Self-referential Structures and Linked List. Programming and Data Structure 1

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

EL2310 Scientific Programming

CS201 Some Important Definitions

Fundamentals of Programming Session 20

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

Character Strings. String-copy Example

Number Review. Lecture #3 More C intro, C Strings, Arrays, & Malloc Variables. Clarification about counting down

Transcription:

CS 237 Meeting 19 10/24/12 Announcements 1. Midterm: New date: Oct 29th. In class open book/notes. 2. Try to complete the linear feedback shift register lab in one sitting (and please put all the equipment away when you are done so it will not get in the way of others who need to use the Macs in that lab). Structs, Pointers, and Recursive Structures 1. Last time, we were considering how to write a C program that would sort numbers by first organizing them into a binary tree so that all the numbers in the left subtree of a node are less than the number in the node and all the numbers in the right subtree of a node are greater than (or equal to) the number in the node. 1 3 4 9 6 Then, the program could extract the numbers in order by completing a pre-order traversal of the tree. 2. We started by looking at a Java program that would sort in this manner using a recursive class to represent trees: 7 8 public IntTree( int value ) { this.value = value; public void preorder( ) { if( left!= null ) { left.preorder(); < System.out.print( value + " " ); if ( right!= null ) { right.preorder(); public void insert( int value ) { if ( value < this.value ) { if ( left == null ) { left = new IntTree( value ); else { left.insert( value ); else { if ( right == null ) { right = new IntTree( value ); else { right.insert( value ); public class IntTree { private int value; private IntTree left; private IntTree right; along with a main method to drive the process: import java.util.*; public class Sort { 1

public static void main( String argv[] ) { Scanner input = new Scanner( System.in ); int value = input.nextint(); IntTree tree = new IntTree( value ); while ( input.hasnextint() ) { tree.insert( input.nextint() ); tree.preorder(); 3. We saw that in C, we need to use pointer types to provide a way to terminate the recursion in a recursive type. For example, to define an inttree structure in C we would say: typedef struct inttree { int value; struct inttree *left; struct inttree *right; *inttree; That is, we will have each structure that represents a tree hold two (possibly null) pointers to its subtrees. 4. Note that we also defined inttree as a pointer type. Most of the time, it will be the pointer type that we need to refer to rather than the structure type. When and if we do need to refer to the structure type we can say struct inttree. Separate Compilation of C Programs 1. Even this program is quite small, we have broken it up into several smaller files to illustrate how this is done in C. First, we will first create a file named inttree.h containing the code typedef struct inttree { int value; struct inttree *left; struct inttree *right; * inttree; // Insert a node for the number value in the // appropriate place in a tree void insert( inttree *rootptr, int value ); // Visit and print the values of all nodes in root void preorder( inttree root ); The typedef in this file describes the struct type used to represent tree nodes. The function headers provide enough information to use the functions associated with the type in the definition of main even though it might be in a different file from the function definitions themselves. In the file containing main, we include a #include for this.h file. #include <stdio.h> #include "inttree.h" inttree root = NULL; // Sort an input file full of integers int main( int argc, char *argv[] ) { // Put all the numbers from the file into a tree int newvalue; while( scanf( "%d", &newvalue ) == 1 ) { insert( &root, newvalue ); // Traverse the tree while printing its contents preorder( root ); // Free all the tree nodes to clean up nicely 2

freetree( root ); Similarly, we include the.h file in the.c file that defines insert and preorder: #include "inttree.h" #include <stdlib.h> #include <stdio.h> // Visit and print the values of all of the nodes in root void preorder( inttree root ) { if ( root!= NULL ) { preorder( root->left ); printf("%d ", root->value ); preorder( root->right ); // Make a new, one-node tree containing a give value inttree newtree( int value ) { inttree result = (inttree) malloc( sizeof( struct inttree ) ); result->value = value; result->left = result->right = NULL; return result; else { insert( &(*rootptr)->right, value ); When invoking the function, put an ampersand in front of the // Insert a node for the number value in the appropriate place variable begin passed. // in a tree 3. When pointers are passed by reference, however, things at least look a void insert( inttree *rootptr, int value ) { little more complicated syntactically. if ( *rootptr == NULL ) { *rootptr = newtree( value ); If you were going to say p->c and try changing it to *p->c else if ( value <= (*rootptr)->value ) { you will discover that the precedence rules are wrong (C tries to insert( &(*rootptr)->left, value ); evaluate the arrow before the star) so you have to write (*p)->c. 3 // Free up the memory allocated for a tree void freetree( inttree root ) { if ( root!= NULL ) { freetree( root->right ); freetree( root->left ); free( root ); Passing Pointers by Reference 1. The insert function in our tree sort code is an example of a C function that takes a pointer variable as a reference parameter. If the method is passed a pointer variable that is NULL, it will update the variable to point to a newly created tree. 2. As in our swap example, we only need to do three things to pass a parameter by reference: Add a star to the declaration of the parameter to indicate that it will hold a pointer to something of the parameter type rather than a value of the parameter type. Throughout the body of the function, use *x instead of x to refer to the parameter (assuming its name is x).

Memory Allocation with malloc 1. The inttree.c file contains a function named newtree that is not mentioned in the.h file. This is an implicit way of making newtree somewhat private. In fact, it could be called from the file containing main, but some warnings would probably be generated since the compiler would not know what types of parameters it expected. 2. This function invokes a very interesting function named malloc. malloc is short for memory allocate. This system function takes one int parameter specifying an amount of memory measured in bytes. It returns a pointer to an available block of memory of the requested size (or a null pointer if the memory requested is not available). The malloc function is declared in the file stdlib.h. That is why the inttree.c file includes this header file. malloc is usually used to allocate space for a value of some particular type. In such cases, the appropriate parameter value to pass to malloc is the number of bytes required to store a value of the type. C provides a sizeof operation (which looks deceptively like a function) that can be applied to a type name or a variable. It returns the size of a value of the type or the type of the variable in bytes. This is why the parameter to malloc in our code is sizeof( struct inttree ). The method is declared to return a value of type void *. That is, it returns a pointer to nothing. Since pointers to nothing are not of much worth, almost all calls to malloc are preceded by a cast that tell C the type of value that the programmer actually plans to store in the allocated memory. This is why the call to malloc in our code is preceded by (inttree). Note: In our code inttree is the type of pointers to structures that represent inttrees. That is struct inttree and inttree are not the same type! Free at Last 1. Unlike Java, C does not have a process that automatically reclaims memory space that has been dynamically allocated (i.e. there is not garbage collector). 2. Instead, a C program must take responsibility for telling the system when it can reuse memory allocated using malloc by invoking a function named free with a pointer to any space that will no longer be used. 3. Our sort program is not a very interesting example of this, because all of the memory is needed until the very end of the program. Nevertheless, our program includes a function that shows how one could free an entire tree of dynamically allocated structures: // Free up the memory allocated for a tree void freetree( inttree root ) { if ( root!= NULL ) { freetree( root->right ); freetree( root->left ); free( root ); Synchronous Sequential Circuits 1. Consider the following attempt to solve the GCD circuit construction exercise included in last week s lab: 4

The clock signal for the other register is the and of the output of the comparator that had been 0 and the main clock. If the comparator changes it output while the main clock is still 1, the second register will see a rising clock pulse and load a new value. TWO REGISTER UPDATES HAVE OCCURRED AT DIFFER- ENT TIMES AS A RESULT OF A SINGLE CLOCK PULSE. This was probably not the intent of the designer of the circuit. 2. This circuit does not work as desired. It is an example of a sequential circuit with a bad synchronization problem. The problems with the circuit are a result of the fact that the clock inputs to the two registers are not tied directly to the clock, but instead are connected to the output of gates whose inputs involve both the clock and circuit elements involving the outputs of the registers. The intent of the circuits design is that the clock signal received by a register will only be 1 if the main clock has been set to 1 and the value in that register is currently greater than the value in the other register. Assuming this is true when the clock first become 1, one register will see a rising clock pulse and load a new value. This new value will quickly become the registers new output. It will be smaller than the old output. It will feed into the comparator used to determine which register should change. If the decrease in value of the register that changed makes it less than the value in the other register, the output of the comparator will change. 3. Things can get even worse. (In fact they were already). The updated comparator output may arrive before the updated output from the combination of the subtraction circuit and multiplexer that determines the input to the registers. In this case, the second register may actually load the wrong (a negative) value. 4. There is a simple design practice for avoiding such race conditions. In a synchronous sequential circuit, all registers have their clock inputs connected to the same signal. It won t arrive at all registers at precisely the same time because of differences in wire lengths, but it will be quite close. 5. This necessitates another way to arrange for some registers to change on a clock pulse when others stay the same. This could be accomplished by placing a multiplexer in front of every register that would choose between a new value and the register s current value. Better yet, real registers (and register in Logisim) usually include an enable input. The register only changes on a clock pulse if this input is 1. 6. A version of the GCD circuit that uses this approach is shown below: 5

6