Midterm Flashcards

1
Q

why is this code “dangerous”?

  1. int test1 = 0;
  2. char line[20];
  3. int test2 = 0;
  4. scanf(“%s”, line);
A

scanf does not honour the size of the target address. it doesn’t let you tell it how much to read

reading input that goes beyond the end of the buffer will overwrite values of other variables (in this case, test1 and test2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

why is this code “dangerous”?

int readData(char *string, int max) {
int read = -1;
FILE *in;
in = fopen( “in.txt”, “r” );
if (in != NULL) {
fgets( string, max, in );
read = strlen( string );
}
return read;
}

A

file is not closed using fclose.
-> the code leaks

could potentially cause the code to crash
- eg. someone could write code to call this function repeatedly

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Here is a physical memory that is pointed by char *str.

How long is this string? (i.e. what will strlen(str) return?)

str -> [a][v][4][0][\0][E][\0][h][\0]

A

4

The string is terminated by the null terminator at str[4].

extra:
- The null terminator is essential because C does not store the length of a string explicitly
-> functions that work with strings rely on the \0 to know where the string ends.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

explain why you would not test for NULL when writing test cases, even as an edge case. (3)

A
  1. testing is meant to simulate user input. users can’t input NULL
  2. Applying the principles of design by contract should catch programming errors (like passing NULL to a
    function)
  3. Passing NULL to a function would cause a Segmentation fault or Abort.
    - A Segmentation fault or Abort isn’t a test failure, it’s a crash.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

passing NULL to a function would cause ________________ or _________

A

segmentation fault or abort

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

what is the main purpose of testing code?

A

to simulate human interaction with our code

(user input)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

what are the 3 general classifications of inputs we need to use to test our code?

A
  1. general cases
    - valid, expected input
  2. edge cases
    - input is valid but looks weird
  3. memory leaks
    - use loops to run code repeatedly
    - observation with tools like top (see man top) or profilers
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

how do you check for memory leaks in your code?

A
  • use loops to run code repeatedly
  • observation with tools like top or profilers
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

list three edge cases for the following in-place sorting routine:

void sort( int *array, int size );

A
  1. array is empty
    - [], 0
  2. array has one value
    - [1]
  3. array has repeated values
    [2, 2, 2]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

the only output you receive when you run a program is Segmentation fault. Explain what tool you would use to identify the problem, and what the tool is helping you understand about the program.

A

asserts, debugger, print statements can all help but for this the best option is a debugger

a debugger helps you:

  1. step through your program line-by-line (observe the flow)
    - helps you find where the code is crashing
  2. watch variables as they change (observe the state)
    - determine which variables have the wrong values that are causing the crash
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Given the following function, what should be the pre and postconditions for the function, and what
should the loop invariant(s) be? Write your answer as a series of assertions. Give at least two examples of
each type

void substr(char *in, int start, int end, char *out) {
int i;
for (i = start; i < end; i++)
out[i - start] = in[i];
out[i] = ‘\0’;
}

A

// preconditions:
assert(in != NULL);
assert(out != NULL);
assert(start < end);
assert(start >= 0);
assert(end < strlen(in));

// loop invariant
assert(i - start >= 0);
assert(i - start < end);

// postconditions
assert(out[0] == in[start]);
assert(out[strlen(out)] == ‘\0’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Below is a structure definition for a string data structure in C:

typedef struct STRING {
char *content;
int length;
} string;

Write a function that will return the index of a character in an instance of this string structure. For complete points, your code must apply the principles of design by contract (you must define pre and postconditions for this function). No invariant function is provided, you should write your own.

Here’s the prototype:
// return the index at the specified character in the string (similar to // Java’s String#indexOf method). Returns -1 if not found.

int index_of(string *, char);

A

see notes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

The degree of reliance on other modules/functions
is called ________

A

coupling

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Higher coupling means higher __________ and we are more likely to be affected [positively/negatively] by changes

A

dependency

negatively

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

The degree to which a function adheres to one task is called __________

A

cohesion

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

_________ cohesion means doing many independent
tasks. is this good?

A

low

no. we want high cohesion. we dont want our functions doing many independent tasks

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

well designed programs should have:

______ cohesion. The elements of each module
should be closely related to one another.
– makes modules easier to use and makes the entire program easier to understand.

_______coupling. Modules should be as independent
of each other as possible.
– makes it easier to modify the program and reuse modules.

A

high

low

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

high cohesion means the elements of each module are what? how does this help?

A

closely related to each other

makes modules easier to use and makes the program easier to understand

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

low coupling means modules should be…

how does this help?

A

as independent of each other as possible

makes it easier to modify the program and reuse modules

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

The assembler translates the assembly to…

A

binary/machine code

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

The von Neumann Architecture

A “stored-program” computer architecture consists of: (4)

A
  • input device
  • output device
  • memory unit
  • central processing unit
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

what is piping for?

A

piping redirects standard output from one program to another to be processed as standard input

transfers standard output to some other destination

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

what are the key differences between C and Java (7/8)

A
  1. C doesn’t have objects
    - no String class. char arrays are strings
  2. C doesn’t garbage collect
    - Java destroys unused arrays and frees memory for you. C does not do this
  3. C doesn’t have exceptions
    - because it doesn’t have objects
    - you must handle exceptional cases yourself
  4. C does not check bounds for you
    - will allow you to overflow and overwrite other blocks of memory
  5. C has no concept of information hiding
    - everything is public
  6. variables can be used without being initialized
  7. arrays
    - not bounds checked
    - array size must be initialized. C doesn’t do this for you. eg. char name[]; // ERROR
    - array data isn’t initialized with 0s (depends)
    - you should initialize them yourself
  8. C gives you direct access to memory
    - there are types but they are just representation of the bits & bytes in memory
    - in Java, bits & bytes are abstracted away into types
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

what is important about C not having objects

A
  • no string class. char arrays are strings
  • no exceptions. must do that shit yourself
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

explain the statement that “C does not garbage collect”

A
  • as variables go out of scope, their resources are not automatically reclaimed
  • the OS has no idea it can use those resources again (leaks)
  • this is also a problem with dynamic memory allocation
  • C doesn’t destroy things for you after you finish using them like Java does
  • this is important because to make efficient use of memory, you must do it yourself
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

cmd 1 | cmd 2

explain whats happening here

A

piping

cmd 1 output is being fed as input to cmd 2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

if the output is going by too quickly to see, what can you do?

A

you can pipe it somewhere (to a pager, like more or less) to view it easier

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

why is it important that C doesn’t have exceptions

A

no try/catch. no bounds checking

  • C will write outside of the bounds and overwrite other information
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

why is it important that C does not check bounds for you?

A

because it wont cause an error. even if the input has too much data for the target address, it will keep going

it will overflow and write over other memory, potentially replacing other variables in your program

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

memory can be thought of as…

A

a long piece of paper

separated into segments that have an address

each segment can store info

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What can function as a Boolean in C?

A

numbers.

0 = false
anything else = true

int i = 10;
while (i){
i–
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

what are some important things to remember for arrays in C

A

not bounds checked

must be passed using pointers

you must initialize the size yourself
- say how much space you’ll need

data in arrays aren’t initialized like in Java
- int array wont necessarily be filled with 0s
- depends on OS

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

how is C compiled?

A
  1. preprocessor
  2. code generator
  3. assembler
  4. linker
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

what is the preprocessor? what does it do?

A

define

a text replacement engine
- finds lines that start with #

  • Replace those lines with file contents (#include)
  • Uses these lines to replace other text in the file (#define)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

what does the code generator do?

where does it take output from?

A
  • generates abstract syntax tree,
  • optimizes it,
  • converts to assembly
  • takes output from preprocessor
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

what does the assembler do

where does it take output from

A

translates assembly to an object file (machine code)

takes output from code generator

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

what does the linker do

where does it take output from

what does it produce?

A

links the functions
- prototypes are important for this
- will get errors from the linker otherwise

takes output from the assembler

Produces an executable binary file

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

how does an array look in memory?

A

contiguous blocks of memory

  • the size you set for an array will reserve that many blocks of memory
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

define exceptions

A

unexpected behaviour

happens during code execution

interrupts flow of execution

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

what are some causes of exceptions?

A
  1. file handling
  2. null pointers
  3. division by 0
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

explain what happens when a function is called

A

a stack frame is created with the memory necessary for the variables in the function

when the function has finished executing, the frame is popped off, and the memory allocated becomes available to the rest of the program

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

explain why stack memory cannot be returned from a function

A

the memory only becomes available after the function is finished executing, and the stack frame gets popped off

any variables held within the stack frame become available and can be rewritten

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

struct vs class in Java

A

struct just has variable declarations
struct does not have methods

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

explain what happens when resources aren’t released after use

A

leaks.

if a function leaks, and is called repeatedly, can cause program to crash

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

what are some programming errors (not at run time)

A

syntax

indexing out of bounds

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

explain design by contract

what does it contain?

A

helps programmer ensure code is running the way they expect it to

contains preconditions, invariants, postconditions

essentially a debugging tool

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

classifications of test data (3)

A
  1. general cases
    - valid and expected input
  2. edge cases
    - valid input that may require special handling
  3. leaks
    - run code repeatedly
48
Q

explain the purpose of automated testing

A

makes it easier for testing throughout changing our program

create template
- saves time in the long run, especially for larger programs

49
Q

strategies for debugging

A
  • printf statements
  • assertions
  • spelunking
  • debugger
50
Q

whats the problem with using printf for debugging?

what can be done about this?

A

printf is buffered
- may not print near the crash

use fflush to ensure buffer is emptied

51
Q

what does debugging reveal

A

flow
- how the program is running. where the crash is

state
- state of variables

52
Q

explain the difference between interface and implementation

what does an interface include?

what does implementation include?

A

interface
- contains min amount of info for a piece of data
- tells you what you can do

  • includes function prototypes
  • data type declaration
  • header files

implementation
- data type definitions
- function implementations

53
Q

classify public interface and private behaviour

A

private behaviour hides implementation
- user doesnt need to know whats going on behind the scenes

54
Q

whats the purpose of a build tool

A

helps us compile our code
- useful for large programs that contain many .c and .h files
- compiling those ourself each time we make a change to our code is a pain in the ass

example: make

55
Q

explain why information/implementation hiding is important

A

hiding implementation allows for the use of programs/code/tools without needing to understand the inner workings

56
Q

is sharing data across scopes ok? why or why not

A

its bad!

  • it exposes implementation
  • it increases coupling
57
Q

identify code that can be separated into modules

A

abstract data types, data structures, and subsystems each get their own module

58
Q

examples of abstract data types

A

lists, queues, stacks

59
Q

examples of data structures

A

linked lists, hash tables

60
Q

what is coupling

A

measurement of how much a class/module/function/concept depends on others

how interdependent

  • coupling is unavoidable but we want to keep it as low as possible
61
Q

what is cohesion

A

measurement of how much code and concepts belong together

  • classes/modules implement ONE concept
62
Q

do we want high or low coupling? why? how can this be helped?

A

we want low coupling

high coupling makes it hard to make changes to our code
- our code is interdependent. changing one thing affects many others

modular design helps avoid coupling

63
Q

how do we reduce coupling?

A

modular design

(what is that?)

64
Q

what is modular design?

A

subdividing a system into smaller parts (modules)

modules can be independently created, modified, replaced

65
Q

what is the purpose of modular design(4)

A
  • breaks code down and makes it easier to read and understand
  • provides abstractable concepts that are easier to use
  • allows multiple ppl to work on same thing
  • allows for dynamic implementation which can be changed and not affect the rest of the program
66
Q

T or F

C gives you the choice for arrays to be placed in “stack memory” or “heap memory”

67
Q

how can you prevent exceptions from occurring

A
  • check that variables have valid values before you use them
  • for now: writing a lot of if statements & checking error codes (invariants)
  • assertions
68
Q

how do we return an array in C

A

using a pointer

69
Q

what is a pointer

A

a type that stores an address

70
Q

what is the basic idea of Output Parameters

A

each function should be responsible for allocating the memory it needs, even if that memory is populated by another function

71
Q

int * x_ptr, y_ptr;

what will these be declared as

A

x_ptr = a pointer
y_ptr = an int

72
Q

Practice: consider the following program. draw it out

int x = 1;
int y = 2;
int z = 3;

int *a, *b;

a = &y;
b = &x;
*b = z;
x = *a;

A

see notes sep 17/19

73
Q

scanf returns one of three things:

A
  1. number of tokens parsed (success)
  2. 0 for a formatting error
  3. EOF for the end of the file
74
Q

how does fgets get input safely? (unlike _______)

A

unlike scanf,

fgets inserts a null terminator at the end of the desired length you set

75
Q

what are the steps to opening a file

A
  1. fopen
    1.5 check if file opened
    - fopen returns NULL if file doesn’t exist
  2. read file
  3. fclose the file
    - only if it opened successfully
76
Q

T or F

C treats stdout as a file

77
Q

what is a class?

A

a “blueprint” for what data and methods go together

78
Q

what is a struct

A

a named grouping of related heterogenous data

like a class but only variables. no methods

79
Q

what is typedef for

A

so that every time we declare a variable of type struct FOO, we DONT have to write struct FOO
- defines foo as a type

80
Q

what happens if you pass a struct as a parameter or return a struct

A

a copy will be made

also, if you assign structs to each other

81
Q

can you compare two structs?

A

no

but you could do a field-by-field comparison to check for duplicates

82
Q

what should you do if you want to modify a struct in a function

A

pass it as a pointer

otherwise you will be working with a copy and wont change the original struct

83
Q

what does malloc do

what does it return

A

requests allocation of heap memory

a pointer to the space in memory it allocated the amount of space you requested (amount of bytes)
- or NULL if it failed

84
Q

malloc takes a size in bytes

whats important to know for this?

A

how many things we want to store

multiplied by:

how many bytes each thing takes up (what type)
- use sizeof

85
Q

different platforms use different amounts of space for the same type. how do we deal with this when using malloc?

A

sizeof
- unary operator that tells us how many bytes a specific data type requires

char * arr = malloc(10 * sizeof(char));
// gives us 10 characters worth of space

86
Q

what should you always remember to do when using malloc?

A

garbage collect!

free memory when we’re done using it
eg. free(array)

87
Q

when we design a data structure, our responsibility is to provide… (2)

hint, one is unique to C

A
  1. a constructor
  2. a destructor
88
Q

what is design by contract a tool for?

what is it not a tool for?

A
  • prevent programming errors
  • exception prevention

NOT for:
- preventing user errors

89
Q

what is the state of a program?

A

the value of all variables that currently exist

90
Q

what kind of programming errors can a programmer write?

A
  • index and bounds errors
  • forget to check inputs (data type, NULL, format)
  • syntax errors (handled by the compiler)
91
Q

exceptions usually come from a violation of our ____________

3 places this can happen:

A

assumptions

  1. before we start processing data
  2. after we finish processing data
  3. the state throughout execution
    (while we’re processing data)
92
Q

char char_at(String* str, int loc){
return str.contents[loc];
}

what are some assumptions we may have about this code?

A
  • loc <= strlen(str)
  • loc >= 0
  • str != null
  • str.contents != null
  • str.contents has a null terminator at position str.length (and this is the first null terminator)
93
Q

the preconditions, postconditions, and invariants of a function/block/thing are its ___________

94
Q

how do we check for leaks?

A

run code repeatedly and see if it crashes

95
Q

what are some edge cases for a sorting algorithm (5)

A

edge cases:
○ a list of length 1
○ a sorted list
○ a reverse sorted list
○ an empty list (length 0)
○ n identical elements

96
Q

preventing exceptions…

what kind of assumptions might we have

A
  • provided arguments are not NULL
  • variables are non-negative
  • values are within bounds of array
  • a counter actually reflects the contents of an object
97
Q

what would some edge cases for a split function be?

(split words separated by spaces)

A
  • “hello” -> no spaces
    – 1 element {“hello”}
    program expects 0 elements
  • “hello, world” -> 2 spaces in a row
    – 2 elements {“hello,”, “world”}
    prgrm expects: 3 elements
  • “ “ only space characters
    – 1 element {“”}(empty string)
    program expects n elements
  • “ hello “ -> space at the beginning and the end
    – 1 element {“hello”}
    program expects 3 elements
  • “” -> empty string
    – 0 element
98
Q

organizing tests:
1. Each test function should be as ______ as
possible
– Test _____ thing. (and test it well.)
2. The data for the test belongs in the test ________.
3. The main function should only call other __________

A

atomic. test one thing

function

functions

99
Q

advantages of typedefs?

A
  • make our program easier to understand
  • make our program easier to modify
100
Q

An __________ type is a type whose values are
listed (“____________”) by the programmer

(same word fits both blanks)

A

enumerated

101
Q

enumerations are a tool for

A

creating types that can only take on a small number of values

eg.
enum suit {
heart,
spade,
club,
diamond
};

enum suit card = heart;

102
Q

whats one thing enumerations are useful for

A

creating a boolean

	typedef enum {
		false, // 0
		true // 1
            } boolean;
103
Q

general strategy for code that crashes

A

key words: flow and state

  1. run the code in the debugger with no breakpoints (run or r)
  2. inspect the stack trace. (bt)
    ○ tell you where the crash is happening
  3. add a break point near the crash. (b or break, followed by the line number)
  4. run program again, stepping through each line after the breakpoint. (n or next)
    - observe state step by step
104
Q

goals of modular design (3)

A
  1. smaller, easier to understand components
  2. ability for multiple ppl to work on program
  3. extract reusable structures and concepts
105
Q

modular design has 2 main parts

(what do we want to do with these two things)

A
  1. the interface of the software
  2. the implementation of the software
    - our main goal is to separate these two things
106
Q

what does a header file contain? (3)

+ (1) extra detail

A
  • function prototypes (public function declarations)
  • struct definitions (as necessary)
  • enum definitions (as necessary)

-> should not expose internal implementation details

107
Q

running the compiler without the linker -c produces __________ files

A

object (.o)

108
Q

what are header guards

A

for when we include the same header more than once

109
Q

Problem: what happens if we include the same header twice?

what can we use to help this?

A

redefinitions -> compilation fails

header guards

110
Q

a makefile consists of a list of ______ that describe how to build a program

a ____ has 3 parts:

A

rules/rule

  1. a target
    ○ the name of the thing this rule generates
  2. a list of prerequisites
    ○ things that must exist before you build this thing
  3. a list of recipes
    ○ the commands that will be run to generate the target

eg. string.c is a prereq for string.o

111
Q

problem: in C, everything is effectively public by default

how do we prevent calling private functions?

A

use “static” modifier

  • in C, static means per-file private
  • ie, this function/data is only available in the file where its declared
112
Q

what is the single responsibility principle

A

each piece should do one thing

113
Q

re: rules

a target is

A

the name of the thing this rule generates

114
Q

re: rules

a list of prerequisites is…

example ?

A

things that must exist before you build this thing

eg. string.c is prereq for string.o

115
Q

re: rules

a list of recipes is…

A

the commands that will be run to generate the target

116
Q

Questions to ask when identifying functions to manipulate your data model: (4)

A
  • what kind of input do you have?
  • how do you get that input?
  • how do you transform it to/from your data model?
  • what kind of operations might someone else need to do? (what are the public operations?)