CSE 333 Midterm Exam 7/27/15 Sample Solution

Similar documents
CSE 333 Midterm Exam Nov. 3, 2017 Sample Solution

CSE 333 Midterm Exam July 24, Name UW ID#

CSE 333 Midterm Exam 5/9/14 Sample Solution

CSE 333 Midterm Exam 7/25/16 Sample Solution. Question 1. (10 points) Preprocessor. Suppose we have the following two files:

CSE 333 Midterm Exam July 24, 2017 Sample Solution

CSE 333 Midterm Exam 2/14/14

CSE 333 Midterm Exam 7/25/16. Name UW ID#

CSE 333 Midterm Exam Sample Solution 5/10/13

CSE 333 Midterm Exam Nov. 3, Name UW ID#

CSE 333 Midterm Exam 5/10/13

CSE 374 Final Exam Sample Solution 3/15/12

CSE au Midterm Exam Nov. 2, 2018 Sample Solution

CSE 303 Final Exam. March 16, 2009

CSE 333 Midterm Exam Sample Solution 7/28/14

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

CSE 333 Midterm Exam Sample Solution 7/29/13

CSE 333 Autumn 2013 Midterm

CSE 374 Final Exam Sample Solution 3/17/11

CSE 333 Midterm Exam 2/12/16. Name UW ID#

CSE 333 Midterm Exam 7/29/13

CSE 374 Final Exam Sample Solution 6/10/10

COMS W3101 Programming Language: C++ (Fall 2015) Ramana Isukapalli

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; }

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

CSE 333 Midterm Exam Cinco de Mayo, 2017 (May 5) Name UW ID#

CSE 303, Autumn 2006, Final Examination 12 December 2006

CSE 374 Final Exam 3/15/17 Sample Solution. Question 1. (8 points) Suppose we have the following two statements in a C program:

Kurt Schmidt. October 30, 2018

Chapter 5. Section 5.4 The Common String Library Functions. CS 50 Hathairat Rattanasook

CSE 374 Final Exam 3/15/17. Name UW ID#

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

PRINCIPLES OF OPERATING SYSTEMS

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

COMS W3101 Programming Language: C++ (Fall 2015) Ramana Isukapalli

CSE 303: Concepts and Tools for Software Development

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

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

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

The University of Nottingham

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

CSE 303, Spring 2006, Final Examination 6 June Please do not turn the page until everyone is ready.

CSE 303, Winter 2007, Final Examination 15 March Please do not turn the page until everyone is ready.

CSE 303, Winter 2007, Final Examination 15 March Please do not turn the page until everyone is ready.

Reliable C++ development - session 1: From C to C++ (and some C++ features)

CSCI-1200 Data Structures Fall 2018 Lecture 7 Templated Classes & Vector Implementation

COP 3223 Introduction to Programming with C - Study Union - Spring 2018

Creating a String Data Type in C

CS240: Programming in C. Lecture 2: Overview

C Introduction. Comparison w/ Java, Memory Model, and Pointers

ANSI C. Data Analysis in Geophysics Demián D. Gómez November 2013

Exercise Session 2 Simon Gerber

Classes in C++98 and C++11

Dynamic memory. EECS 211 Winter 2019

CSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation

CSE 333 Lecture 7 - final C details

Short Notes of CS201

Intermediate Programming, Spring 2017*

CSE 374 Midterm Exam Sample Solution 2/11/13. Question 1. (8 points) What does each of the following bash commands do?

CS201 - Introduction to Programming Glossary By

ECE551 Midterm. There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly.

C++_ MARKS 40 MIN

Question 1. Part (a) CSC 209H1 S 2017

CSC209H1S Day Midterm Solutions Winter 2010

The output will be: marks all or nothing. 1 #include <stdio.h> 2 main() { 3 int i; int j; 4 int *p; int *q; 6 p = &i; 7 q = &j; 8 i = 1;

CA341 - Comparative Programming Languages

Pointers, Dynamic Data, and Reference Types

CSE 374 Final Exam 06/06/18. Question 1 (8 points). Preprocessor. Consider the following program: #include <stdio.h>

CSE 303, Winter 2007, Midterm Examination 9 February Please do not turn the page until everyone is ready.

CSCI-1200 Data Structures Spring 2013 Lecture 7 Templated Classes & Vector Implementation

CS349/SE382 A1 C Programming Tutorial

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

ECE551 Midterm Version 1

University of Toronto

CS 241 Data Organization Binary Trees

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

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

ECE 2035 Programming HW/SW Systems Spring problems, 5 pages Exam Three 8 April Your Name (please print clearly)

Fast Introduction to Object Oriented Programming and C++

Final CSE 131B Spring 2004

Overview of today s lecture. Quick recap of previous C lectures. Introduction to C programming, lecture 2. Abstract data type - Stack example

Lectures 5-6: Introduction to C

CS201- Introduction to Programming Current Quizzes

Bruce Merry. IOI Training Dec 2013

ECE 15B COMPUTER ORGANIZATION

CS61C Machine Structures. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

C for C++ Programmers

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Deep C by Olve Maudal

CIS 190: C/C++ Programming. Classes in C++

11 'e' 'x' 'e' 'm' 'p' 'l' 'i' 'f' 'i' 'e' 'd' bool equal(const unsigned char pstr[], const char *cstr) {

Lectures 5-6: Introduction to C

CS2141 Software Development using C/C++ C++ Basics

C Programming Basics II

CSCI 2132 Final Exam Solutions

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

C mini reference. 5 Binary numbers 12

Transcription:

Question 1. (24 points) C programming. In this problem we want to implement a set of strings in C. A set is represented as a linked list of strings with no duplicate values. The nodes in the list are defined as follows: typedef struct snode_t { char * str; // string on the heap owned by this node struct snode_t * next; // next node in in the set SNode; An empty set is represented by an empty list (NULL). When a string is added to the set, a copy of the string is made on the heap (allocated with malloc) so that the strings referenced by the set are not shared with strings in client programs. The nodes are also allocated on the heap. A diagram of a set containing strings abc and xyz would look like this (although the strings could be stored in any order): a b c \0 x y z \0 Your job is to implement functions contains and add for this data structure. Client code uses these functions as follows: SNode * set = NULL; // set of strings, initially empty add(&set, "xyz"); // add xyz to the set printf("%d\n", contains(set, "abc")); // prints 0 printf("%d\n", contains(set, "xyz")); // prints 1 add(&set, "xyz"); // no change xyz already in set add(&set, "abc"); // set now contains abc and xyz Write implementations of functions contains and add on the next pages. You need to fill in the parameter types as well as the bodies of the functions. The parameters types should be chosen so that the above client code will compile and run properly. Your implementation of add should use contains to decide if a string is already in the set and should not change the set if the string is already included. Some useful string functions, if you need them. All string arguments have type char*. strlen(s) returns the number of characters (bytes) in s, not including the \0 byte at the end. strcpy(dst,src) copies src to dst. strcat(dst,str) appends a copy of src to the end of dst. strcmp(x,y) returns 0 if strings x and y are the same, some negative integer if x<y, and some positive integer if x>y. Page 1 of 8

Question 1. (cont.) (a) (10 points) Implement function contains. Be sure to supply parameter types. // return 1 if set st contains string s, otherwise return 0 int contains( SNode * st, char * s) { SNode * p = st; while (p!= NULL) { if (strcmp(s, p->str) == 0) return 1; p = p->next; // not found (b) (14 points) Implement function add. Be sure to supply parameter types. Constraint: use contains to decide whether the string is already included in the set. // Add string s to set st if it is not already a member. // Return 1 if st was changed to add s, otherwise return 0. // If s is added to st, a copy of s is allocated on the // heap. If any storage allocation fails, leave the set // unchanged and return 0. int add( SNode ** st, char * s) { if (contains(*st, s)) { // not found. allocate copy of s on the heap and // add to the set SNode * n = (SNode *)malloc(sizeof(snode)); if (n == NULL) { n->str = (char *)malloc(strlen(s)+1); if (n->str == NULL) { free(n); strcpy(n->str, s); n->next = *st; *st = n; return 1; Page 2 of 8

Question 2. (12 points) Preprocessor. Consider the following C++ (not C) program, which does compile and execute successfully. #include <iostream> using namespace std; #define TEST #ifdef TEST #define CHECK(x) incr(x) #else #define CHECK(X) #endif void incr(int &n) { n++; cout << "incr: " << n << endl; int main() { int x = 0; CHECK(x); x += 42; cout << "x = " << x << endl; CHECK(x); cout << "x = " << x << endl; (a) (6 points) What does this program print when it is compiled and executed? incr: 1 x = 43 incr: 44 x = 44 (b) (6 points) Now suppose we remove the single line #define TEST from the top of the program, recompile it, and run it again. What does it print after this change? x = 42 x = 42 Page 3 of 8

Question 3. (12 points) Making stuff. Here is the Makefile for a small application similar to the one used as an example in class. foobar: main.o foo.o bar.o dictionary.o gcc -Wall g -std=c11 -o foobar main.o foo.o bar.o dictionary.o main.o: main.c foo.h bar.h dictionary.h gcc -Wall -g -std=c11 -c main.c foo.o: foo.c foo.h dictionary.h gcc -Wall -g -std=c11 -c foo.c bar.o: bar.c bar.h foo.h gcc -Wall -g -std=c11 -c bar.c dictionary.o: dictionary.c dictionary.h gcc -Wall -g -std=c11 -c dictionary.c clean: rm -rf foobar *.o *~ The summer intern working on this program has changed the code slightly, but doesn t understand how to update the Makefile appropriately. The changes to the code are: 1. Two new files have been added: dictionary.h and dictionary.c. These declare and implement a new data structure used in the program. 2. Files foo.c and main.c have been changed to use this new data structure by adding #include "dictionary.h" to each of these C files. Alter the above Makefile to take these changes into account. The modified Makefile should work as expected: the new data structure files should be compiled and linked with the rest of the program, and files should be recompiled only when needed. Write your changes directly on the Makefile above. Page 4 of 8

Question 4. (12 points) Bugs R Us. Each of the following C functions has a memory management error. Briefly explain what could or will go wrong when the code is executed. (a) (6 points) void f(int * p) { free(&p); The function attempts to free a local variable on the stack. But the argument to free must be a pointer value that was returned from a call to malloc. (Note: several answers said that the code should be changed to free(p). That does fix the frees-a-local bug, but is not necessarily right. It is only correct if p is a pointer to something allocated by malloc, but we have no guarantee that it is.) (b) (6 points) int h(int, int*); // external helper function declaration int * g(int sz) { int * ans = (int*)malloc(sz*sizeof(int)); int ok = h(sz,ans); if(ok) return ans; else return g(sz*2); // recur with bigger size If h returns 0 (false) the function has a memory leak. The memory allocated by malloc becomes unreachable and is never freed. Page 5 of 8

Question 5. (20 points) Pointy things. Consider the following program, which compiles and executes with no warnings or errors: #include <stdio.h> void g(int **x, int *y, int *z) { **x = 10; *x = z; // HERE!!! (see below) // printf("g: %d %d %d\n", **x, *y, *z); void f(int *q, int n, int *p) { n = n+2; *p = *p**q; g(&q, &n, p); printf("f: %d %d %d\n", *p, *q, n); int main() { int a = 7; int b = 2; f(&a, b, &b); printf("main: %d %d\n", a, b); (a) (14 points) Draw a boxes n arrows diagram showing the memory layout and contents at the point just before the printf in function g is executed (marked with HERE!!! in the comment). Be sure your diagram clearly shows the values of all variables in all active functions and has a separate box or stack frame for each function. For each pointer, draw an arrow from the pointer to the variable that it references. Use the space below the code and/or to the right for your diagram. (b) (6 points) What does this program print when it is executed? g: 14 4 14 f: 14 14 4 main: 10 14 Page 6 of 8

Question 6. (20 points) A bit of C++ hacking. In class we demonstrated a simple string class named Str. This class provides strings with operations like append, length, and assignment. Regular heap-allocated C strings (\0-terminated array of characters) were used in the implementation. Here is a subset of the class declaration in Str.h: class Str { public: // constructors Str(); Str(const char *s);... private: // Str representation char *st_; ; // create empty Str // create Str from c-string s // c-string on heap with '\0' terminator And here is the implementation of those two constructors from Str.cc: Str::Str() { st_ = new char[1]; st_[0] = '\0'; Str::Str(const char *s) { int len = strlen(s); st_ = new char[len+1]; strcpy(st_, s); We would like to add a += operator to this class. This new operator should update a string by appending a second string to it. For example, the sequence Str s("hello"); Str t(" there"); s += t; cout << s << endl; should print hello there. The += operation is an assignment operation, so it should have the proper type and result so that chained assignments like s+=t+=u work properly. Write your answers on the following page. Feel free to detach this page for reference while you work. Page 7 of 8

Question 6. (cont.) (a) (6 points) Give a correct declaration for the new Str += operator. This is the declaration that should be added to the Str class declaration in Str.h. Str & operator+=(const Str &s); (b) (14 points) Write an implementation of the += operator as it would appear in Str.cc. You must implement this operation directly and not call other functions in class Str. You will, of course, need to use functions from the C string library to process the underlying string arrays, and you should use those. Str & Str::operator+=(const Str &s) { char *newst = new char[strlen(st_) + strlen(s.st_) + 1]; strcpy(newst, st_); strcat(newst, s.st_); delete [] st_; st_ = newst; return *this; (This is almost exactly the same as the append function that was included in the Str example. The difference is the function name, return type, and return value.) Page 8 of 8