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.

Similar documents
ECE551 Midterm Version 1

ECE551 Midterm Version 1

ECE551 Midterm Version 2

ECE 551D Spring 2018 Midterm Exam

ECE 551D Spring 2018 Midterm Exam

Signature: ECE 551 Midterm Exam

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.

Procedural Programming

C mini reference. 5 Binary numbers 12

ECE264 Fall 2013 Exam 3, November 20, 2013

Lecture 05 Pointers ctd..

Lab # 4. Files & Queues in C

Characters and Strings

Student Number: Instructor: Reid Section: L0101 (10:10-11:00am)

Student Number: Instructor: Reid Section: L5101 (6:10-7:00pm)

This code has a bug that allows a hacker to take control of its execution and run evilfunc().

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1

Contents. A Review of C language. Visual C Visual C++ 6.0

MARKS: Q1 /20 /15 /15 /15 / 5 /30 TOTAL: /100

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

CSE 333 Midterm Exam Sample Solution 7/28/14

Dynamic memory. EECS 211 Winter 2019

211: Computer Architecture Summer 2016

Winter 2017 CS107 Midterm #2 Examination (Practice #2) Problem Points Score Grader TOTAL 30

CSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation

Pointers, Arrays, and Strings. CS449 Spring 2016

File IO and command line input CSE 2451

ECE264 Spring 2013 Exam 1, February 14, 2013

Procedural Programming & Fundamentals of Programming

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

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

Course organization. Course introduction ( Week 1)

Winter 2017 March 2, 2017 CS107 2 nd Midterm Examination

Student Number: Instructor: Reid Section: L0201 (12:10-1:00pm)

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

CSE 333 Midterm Exam July 24, Name UW ID#

CSCI 171 Chapter Outlines

CS1003: Intro to CS, Summer 2008

ECE264 Spring 2014 Exam 2, March 11, 2014

Reading Assignment. Strings. K.N. King Chapter 13. K.N. King Sections 23.4, Supplementary reading. Harbison & Steele Chapter 12, 13, 14

8. Characters, Strings and Files

Midterm Examination # 2 Wednesday, March 18, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

ECE264 Spring 2013 Final Exam, April 30, 2013

CSE351 Spring 2018, Final Exam June 6, 2018

a) Write the signed (two s complement) binary number in decimal: b) Write the unsigned binary number in hexadecimal:

SYSTEM AND LIBRARY CALLS. UNIX Programming 2015 Fall by Euiseong Seo

Q1: /20 Q2: /30 Q3: /24 Q4: /26. Total: /100

CSE 333 Midterm Exam 2/14/14

Fundamentals of Programming & Procedural Programming

CSE 303 Midterm Exam

14. Memory API. Operating System: Three Easy Pieces

Princeton University Computer Science 217: Introduction to Programming Systems. Modules and Interfaces

Creating a String Data Type in C

Midterm Review. What makes a file executable? Dr. Jack Lange 2/10/16. In UNIX: Everything is a file

Mid-term Exam. Fall Semester 2017 KAIST EE209 Programming Structures for Electrical Engineering. Name: Student ID:

TI2725-C, C programming lab, course

C programming basics T3-1 -

Lecture 8 Dynamic Memory Allocation

The University of Calgary. ENCM 339 Programming Fundamentals Fall 2016

Getting Started. Project 1

Memory Management. CSC215 Lecture

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

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

Understanding Pointers

C strings. (Reek, Ch. 9) 1 CS 3090: Safety Critical Programming in C

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

Midterm Examination # 2 Wednesday, March 19, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

CSE 333 Midterm Exam 7/27/15 Sample Solution

C Structures & Dynamic Memory Management

Object Oriented Programming COP3330 / CGS5409

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

Computer Programming: Skills & Concepts (CP) Strings

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

Dynamic memory allocation

SOFTWARE Ph.D. Qualifying Exam Spring Consider the following C program which consists of two function definitions including the main function.

ECE264 Fall 2013 Exam 1, September 24, 2013

Mid-term Exam. Fall Semester 2017 KAIST EE209 Programming Structures for Electrical Engineering. Name: Student ID:

19-Nov CSCI 2132 Software Development Lecture 29: Linked Lists. Faculty of Computer Science, Dalhousie University Heap (Free Store)

[6 marks] All parts of this question assume the following C statement. Parts (b) through (e) assume a variable called ptrs.

C for C++ Programmers

CSE 12 Spring 2016 Week One, Lecture Two

CS 261 Fall Mike Lam, Professor. Structs and I/O

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

by Pearson Education, Inc. All Rights Reserved.

CSCE150A. Introduction. Basics. String Library. Substrings. Line Scanning. Sorting. Command Line Arguments. Misc CSCE150A. Introduction.

Jacobs University Bremen February 7 th, 2017 Dr. Kinga Lipskoch. Practice Sheet. First Name:... Last Name:... Matriculation Number:...

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

CSE 333 Midterm Exam July 24, 2017 Sample Solution

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 9. Strings. Notes. Notes. Notes. Lecture 07 - Strings

Midterm Exam Nov 8th, COMS W3157 Advanced Programming Columbia University Fall Instructor: Jae Woo Lee.

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

Computer Science & Engineering 150A Problem Solving Using Computers

Memory Management I. two kinds of memory: stack and heap

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060

Strings. Arrays of characters. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY

CS 33. Intro to Storage Allocation. CS33 Intro to Computer Systems XXVI 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

Programs in memory. The layout of memory is roughly:

Carnegie Mellon. C Boot Camp. September 30, 2018

Transcription:

Name: ECE551 Midterm NetID: There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual work. You may not collaborate with your fellow students. However, this exam is open book and open notes. You may use any printed materials, but no electronic nor interactice resources. I certify that the work shown on this exam is my own work, and that I have neither given nor received improper assistance of any form in the completion of this work. Signature: # Question Points Earned Points Possible 1 Multiple Choice Concepts 8 2 Reading Code 7 3 Debugging 8 4 Coding 1: Strings 7 5 Coding 2: Arrays 10 6 Coding 3: Dynamic Allocation 15 7 Coding 4: File IO 20 Total 75 Percent 100 The next two pages contains some reference (an abbreviated version of the man pages) for common, useful library functions. 1

char * strchr(const char *s, int c); The strchr function locates the first occurrence of c (converted to a char) in the string pointed to by s. It returns a pointer to the located character, or NULL if the character does not appear in the string. char * strdup(const char *s1); The strdup function allocates sufficient memory for a copy of the string s1, does the copy, and returns a pointer to it. The pointer may subsequently be used as an argument to the function free. If insufficient memory is available, NULL is returned. size_t strlen(const char *s); The strlen function computes the length of the string s and returns the number of characters that precede the terminating \0 character. int strcmp(const char *s1, const char *s2); int strncmp(const char *s1, const char *s2, size_t n); The strcmp and strncmp functions lexicographically compare the null-terminated strings s1 and s2. The strncmp function compares not more than n characters. Because strncmp is designed for comparing strings rather than binary data, characters that appear after a \0 character are not compared. These functions return an integer greater than, equal to, or less than 0, according as the string s1 is greater than, equal to, or less than the string s2. The comparison is done using unsigned characters. char *strstr(const char *s1, const char *s2); The strstr function locates the first occurrence of the null-terminated string s2 in the null-terminated string s1. If s2 is an empty string, s1 is returned; if s2 occurs nowhere in s1, NULL is returned; otherwise a pointer to the first character of the first occurrence of s2 is returned. void * malloc(size_t size); The malloc function allocates size bytes of memory and returns a pointer to the allocated memory. void * realloc(void *ptr, size_t size); The realloc function creates a new allocation of size bytes, copies as much of the old data pointed to by ptr as will fit to the new allocation, frees the old allocation, and returns a pointer to the allocated memory. If ptr is NULL, realloc is identical to a call to malloc for size bytes. void free(void *ptr); The free function deallocates the memory allocation pointed to by ptr. If ptr is a NULL pointer, no operation is performed. int fgetc(file *stream); The fgetc function obtains the next input character (if present) from the stream pointed at by stream, or EOF if stream is at end-of-file. 2

char * fgets(char * str, int size, FILE * stream); The fgets function reads at most one less than the number of characters specified by size from the given stream and stores them in the string str. Reading stops when a newline character is found, at end-of-file or error. The newline, if any, is retained. If any characters are read and there is no error, a \0 character is appended to end the string. Upon successful completion, it returns a pointer to the string. If end-of-file occurs before any characters are read, it returns NULL. ssize_t getline(char ** linep, size_t * linecapp, FILE * stream); The getdelim() function, delimited by the character delimiter. The getline function reads a line from stream, which is ended by a newline character or end-of-file. If a newline character is read, it is included in the string. The caller may provide a pointer to a malloced buffer for the line in *linep, and the capacity of that buffer in *linecapp. These functions expand the buffer as needed, as if via realloc. If linep points to a NULL pointer, a new buffer will be allocated. In either case, *linep and *linecapp will be updated accordingly. This function returns the number of characters written to the string, excluding the terminating \0 character. The value -1 is returned if an error occurs, or if end-of-file is reached. void * memcpy(void * dst, const void *src, size_t n); The memcpy function copies n bytes from memory area src to memory area dst. 3

Question 1 Multiple Choice Concepts [8 pts] Q1.1 Suppose you have the following declarations: int x; int * p; int **q ; What are the types of each of the following expressions? 1. &x 2. *p 3. &q 4. *&x (a) int (b) int * (c) int ** (d) int*** (e) None of the above (or illegal) (a) int (b) int * (c) int ** (d) int*** (e) None of the above (or illegal) (a) int (b) int * (c) int ** (d) int*** (e) None of the above (or illegal) (a) int (b) int * (c) int ** (d) int*** (e) None of the above (or illegal) 4

Q1.2 A programmer wrote the following code to read a line from stdin, split it at the dot(. ) character, and store the two pieces into a struct. struct somestruct x; //type somestruct declared elsewhere x.str1 = NULL; size_t sz = 0; if(getline(&x.str1, &sz, stdin) > 0) { x.str2 = strchr(x.str1,. ); if (x.str2 == NULL) { //some error handling *x.str2 = \0 ; x.str2++; Which of the following correctly frees the memory allocated in this code fragment? A. free(x.str1); free(x.str2); B. free(x.str2); free(x.str1); C. free(x.str1); free(x.str2); free(x); D. free(x.str1); free(x.str2); free(&x); E. None of the above 5

Q1.3 Suppose you are white-box testing the following code: int myfunction(int a, int b, int c) { int answer = c * a; if(a < b) { if (b % 2 == 0) { answer += c; if (a > c) { answer += b; else { answer -= b; return answer; You use the test cases below (in the order they appear). For each test case listed below, select the level of test coverage that you have obtained by executing that test case along with all test cases that appear above it: 1. a=0, b=0, c=0 (a) None (b) Statement (c) Decision (d) Path 2. a=2, b=3, c=1 (a) None (b) Statement (c) Decision (d) Path 3. a=2, b=4, c=1 (a) None (b) Statement (c) Decision (d) Path 4. a=9, b=7, c=8 (a) None (b) Statement (c) Decision (d) Path For extra credit: What is the minimum possible number of test cases required to obtain path coverage (not necessarily using these cases, but if they are carefully constructed specifically to get path coverage in as few as possible). To answer write only the number below. Minimum test cases for path coverage: 6

Question 2 Reading Code [7 pts] Execute the following code by hand, and fill in the output at the bottom of this page (the start of each line is written for you, write the correct number at the end of each line). #include <stdio.h> #include <stdlib.h> int * f (int *a, int * b) { int n = *b; a[n] += a[n-1]; *b += a[0]; return &a[2]; void g(int n, int ** q) { n+= 27; (**q) += 9; (*q)++; int main(void) { int data[] = {4, 8, 9, 10; int x = 3; int * p = f(data, &x); printf("data[3] = %d\n",data[3]); printf("x = %d\n", x); g(x,&p); *p = *p * 2; for (int i =0; i < 4; i++) { printf("data[%d] = %d\n", i, data[i]); printf("x = %d\n", x); return EXIT_SUCCESS; Fill in output below: data[3] = x = data[0] = data[1] = data[2] = data[3] = x = 7

Question 3 Debugging [8 pts] A C programmer wrote the following buggy code to try to split the contents of a file up at each comma (, ). With the help of the valgrind errors on the next page, identify the correct remedy for each problem: 1: struct _string_arr_t { 2: char ** strs; 3: size_t n; 4: ; 5: typedef struct _string_arr_t string_arr_t; 6: 7: string_arr_t * splitbycommas(file * f) { 8: string_arr_t * ans = malloc(sizeof(*ans)); 9: ans->strs = NULL; 10: ans->n = 0; 11: char * line; 12: size_t sz = 0; 13: while (getline(&line, &sz, f) > 0) { 14: char * ptr = line; 15: while (ptr!= NULL) { 16: char * commaptr = strchr(ptr,, ); 17: char * newstr; 18: *commaptr = \0 ; 19: newstr = strdup(ptr); 20: ptr = commaptr+1; 21: ans->strs = realloc(ans->strs, ans->n + 1); 22: ans->strs[ans->n] = newstr; 23: ans->n++; 24: 25: 26: return ans; 27: 8

Error 1 The first problem is: Conditional jump or move depends on uninitialised value(s) at 0x4EA6002: getdelim (iogetdelim.c:63) by 0x400850: splitbycommas (f15.c:13) by 0x400882: main (f15.c:41) This problem can be correctly fixed by: A. Passing line instead of &line to getline on line 13. B. Passing *line instead of &line to getline on line 13. C. Changing line 11 to read char * line = NULL; D. Changing line 11 to read char ** line; E. None of these Error 2 After correctly fixing the first problem, the next error is: Invalid write of size 1 at 0x400799: splitbycommas (f15.c:18) by 0x400869: main (f15.c:41) Address 0x0 is not stack d, malloc d or (recently) free d Process terminating with default action of signal 11 (SIGSEGV) Access not within mapped region at address 0x0 at 0x400799: splitbycommas (f15.c:18) by 0x400869: main (f15.c:41) This problem can be correctly fixed by: A. Deleting line 18 completely B. Changing line 18 to read **commaptr= \0 ; C. Changing line 18 to read commaptr = NULL; D. Changing line 18 to read commaptr = \0 ; E. None of these 9

Error 3 After correctly fixing the first two problems, the next error is: Invalid write of size 8 at 0x400818: splitbycommas (f15.c:22) by 0x400882: main (f15.c:41) Address 0x51fc1a0 is 0 bytes inside a block of size 1 alloc d at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) by 0x4C2CF1F: realloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) by 0x4007F6: splitbycommas (f15.c:21) by 0x400882: main (f15.c:41) This problem can be correctly fixed by: A. Changing realloc s second argument on line 21 to (ans->n + 1) *sizeof(ans->strs) B. Changing realloc s second argument on line 21 to (ans->n + 1) *sizeof(*ans->strs) C. Changing realloc s second argument on line 21 to (ans->n + 1) *sizeof(**ans->strs) D. Changing realloc s second argument on line 21 to (ans->n + 2) *sizeof(ans->strs) E. None of these Error 4 After correctly fixing the first three errors, the code runs, but leaks memory: 120 bytes in 1 blocks are definitely lost in loss record 1 of 1 at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) by 0x4EA6024: getdelim (iogetdelim.c:66) by 0x400858: splitbycommas (f15.c:13) by 0x40087E: main (f15.c:41) This error can be corrected by: A. Placing free(line); between lines 24 and 25 (in the while loop) B. Placing free(line); between lines 25 and 26 (after the while loop) C. Placing line = NULL; between lines 24 and 25 (in the while loop) D. Placing line = NULL; between lines 25 and 26 (after the while loop) E. None of these 10

Question 4 Coding 1: Strings [7 pts] Write your own implementation of the strchr function from the C library (it is described in the reference material at the start of this exam), without using any library functions: char *strchr(const char *s1, int c) { 11

Question 5 Coding 2: Arrays [10 pts] The dot product of equal-length vectors (A = a 0, a 1, a 2,..a n and B = b 0, b 1, b 2,... b n ) is A B = a 0 b 0 +a 1 b 1 +a 2 b 2 +... a n b n. For example, 1, 3, 5 2, 4, 6 = 1 2+3 4+5 6 = 44. Assuming that you use the type vect_t (defined below) to represent mathematical vectors, write the dotproduct function which takes two vectors and computes their dot product. You should use assert to check any necessary conditions of the inputs (that is, if the function is given improper input, it should fail an assert that you wrote prior to using the invalid input). struct _vect_t { double * values; size_t n; ; typedef struct _vect_t vect_t; double dotproduct(vect_t a, vect_t b) { 12

Question 6 Coding 3: Dynamic Allocation [15 pts] Write your own implementation of the realloc function from the C library (it is described in the reference material at the start of this exam), without using any library functions except for malloc, free, or memcpy (you do not HAVE to use these, but they are the only ones you MAY use): You will need to inspect the size of the current allocation of ptr, which is not generally possible, so you may make use of the (made-up) function size_t allocsize(void* ptr) which will return to you how many bytes are currently allocated to the block pointed to by ptr. void * realloc(void *ptr, size_t size) { 13

Question 7 Coding 4: File IO [20 pts] Write a program which takes 2 command line arguments (which are the names of files). The first argument names the input file name, and the second names the output file. Your program should read the contents of the input file, reverse the order of the lines (but not the contents of each line), and write these lines into the output file. For example, if the input file contains I like apples. That dragon is large. Owls fly quietly. then you program should write the following into the file named by its second command line argument: Owls fly quietly. That dragon is large. I like apples. For this problem, we will relax the no assumptions restriction by allowing you to assume that (1) two command line arguments are provided (2) the input file requested exists and is readable (3) the output file is writeable (so fopen succeeds for both) (3) malloc and realloc always succeed (4) fclose succeeds. You may use any library functions you wish. You may NOT assume anything about the length of the longest line in the file. Answer on next page (You may use this area for scratch work) 14

#include <stdio.h> #include <stdlib.h> 15