C family Flashcards

1
Q

Why can C be referred to as being almost a portable assembly language

A

It is as close to the machine as possible while it is almost universally available for existing processor architectures.

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

What does the statement “C is imperative” mean?

A

It describes computation in terms of statements that change a program state

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

What does the statement “C is declarative” mean?

A

describes computation in terms of what it should accomplish

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

C is a procedural/functional language

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

What does the statement “C is weakly typed” mean?

A

C supports implicit type conversion

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

What does the statement “C is statically typed” mean?

A

Types are checked before runtime so variables must be declared

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

What are compiler directives and some examples?

A

Special instructions that guide the preprocessor
#include will include the contents of another file - usually containing function prototypes and variable declarations

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

What is the difference between float, double and long double

A

While they are both floating point numbers, double is larger and long double is larger still

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

How much memory does a char, short int, int and long int take up?

A

char - 1 byte
short int - 2 bytes
int - 4 bytes
long int - 8 bytes
(unsigned versions take up the same amount of memory)

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

To what precision can a float, double and long double hold data and how much memory do they take up?

A

Float, 6 digits, 4 bytes
double, 15 digits, 8 bytes
long double, 18 digits, 16 bytes

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

As there is no boolean datatypes in ANSI C, how are conditions evaluated?

A

0 is considered false while any other value is considered true

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

How can i create AND and OR conditional statements

A

Double ampersand for AND: &&
Double straight liney thing for OR: ||

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

What is an advantage and disadvantage of using code short-hands

A

Adv: reduce time to type - may reduce codesize

DisAdv: do not execute any faster and may make code harder to follow

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

What do break and continue statements do?

A

Break will break out of the loop and jump to the next command
Continue will jump to the start of next iteration

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

What is the difference between a While and a Do While loop?

A

While loop will check the condition before executing
Do While will execute once before checking the condition is true

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

What does “pass by value” mean for functions in C

A

The value of the variable is passed into the function and the value can be used in further calculations. The value of the original variable is not changed

f(variable_name)

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

What does “pass by reference” mean for functions in C

A

A pointer to the variable is passed to the function, that way processing can be done on the variable and it’s actual value will change

f(*variable_name)

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

How can we get around C’s functions only being able to return one value if we want to change multilpe

A

Through the use of pointers, if multiple pointers are fed into the function then the values of multiple variables can be changed

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

How should we pass arguments into the main function from the command line?

A

It must be defined like this:

int main(int argc, char **argv)

Arg c contains the number of arguments passed and argv is an array of string values. This is not required but is suggested heavily by convention

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

What are the values of argv if the program is called myProgram

myProgram Hello 3 “a short sentence”

A

argv[0] = myProgram
argv[1] = Hello
argv[2] = 3
argv[3] = a short sentence

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

What are two advantages to using pointers to functions?

A

Functions can be passed as arguments to other functions, oft called callback functions

We can choose which function to execute at runtime based on user inputs

There’s something about qSort on lecture 3 but cba to figure it out

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

How are arrays stored in memory?

A

Arrays are stored contiguously in memory, when an array is initialized an appropriate amount of memory will be reserved

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

How are strings stored in C and what does it mean for a string to be unitialised?

A

A string is stored contiguously as an array of characters, ending in a NULL terminating character ‘\0’.
An string is uninitialized if it hasn’t had characters assinged to it and will contain random stuff until it does

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

What is a null terminator and what will happen if one does not exist?

A

The null terminator (‘\0’) tells printf when to stop printing out characters

If your string does not have a null terminator, printf carries on plodding through memory and printing out characters until it encounters one.

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

What will these print statements output?

char name [21] = “Elephants”;

printf(“%s\n”, name);

printf(“%20s\n”, name);

printf(“%-20s\n”, name);

printf(“%3s\n”, name);

printf(“%-20.3s\n”, name);

A

They will output:

Elephants

  • Elephants*

*Elephants *

Elephants

*Ele *

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

Does the strlen function return the length of a string with or without the null terminator?

A

It will return it without

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

what does strcpy(fullName, firstname) do ?

A

this will copy the string held in fullName into firstName

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

What will strcat(str1, str2) do?

A

will concatonate str2 onto the end of str1, overwriting str1

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

How does strcmp(str, str2) work?

A

This function will return 0 if the two strings are the same, if otherwise it will return another int value

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

What will this statement do?

sprintf(fullName, “%s %s”, fullName, lastName)

A

Works very similar to a printf statement but the output of the printf is stored in fullName

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

What is a uniform random number distribution?

A

A distribution where all values in a defined range are equally likely

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

Why can we not use rand() for statistical modelling?

A

It does not produce high quality randomness and it not suitable for statistical modelling.
It is okay to use if a program just needs a bit of randomness

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

How does seeding work in C and how can srand statements be used?

A

Seeding refers to the process of initializing a pseudo-random number generator. Without seeding, a rand() will always start from the same internal state, leading to the same sequence of “random” numbers every time you run the program.

Seeding is can be a user inputted number but time is often recommended

used like:

srand(43);

srand(time(0));

The second option is the only one that will produce a different number each run

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

What does scanf do?

A

Will capture a user input which can then be stored

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

What is a stream?

A

It’s an abstraction of a file - this means that a consistent interface can be provided to the programmer
stdio.h much be included

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

What does it mean that a stream is buffered?

A

Data is not necessarily written to the device when the write command is issued, however this can be forced by flushing the stream

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

What are the two types of stream?

A

Text stream - sequence of characters - character translation may occur

binary stream - sequence of bytes - character translation will not occur

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

What are three common functions used to write to a stream - including binary streams

A

putc() or fputc(ch, fp) - will write a character to a stream

fputs(str, fp) - write a string to the stream

fwrite() - writes to a binary stream

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

What are three common functions used to read from a stream?

A

getc() or fgetc(fp) - read a character from a stream and can store it in a variable

fgets(str, count, fp) - read a string from a stream up to a max of count characters and stores it in str

fread() - read from a binary stream

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

When reading/writing to a stream what is something that must always be tested?

A

You must always test that opening the file was successful

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

What do these file modes mean?
r
w
a
rb
wb

A

read
write
appending to
read a binary file
write to a binary file

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

What does fprintf() do?

A

Works like a printf statement but will ouput the string to the file pointed to by fo

fprintf(fp, “String stuff %s”, ch)

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

what does fscanf do?

A

fscanf(fp,”%d,%d”,&x,&y);
like scanf, but the string is input from the file pointed to by fp

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

What do the following stream functions do?
fflush(fp)
remove(“MyFile.txt”)
rewind(fp)

A

fflush(fp) - forces the output buffer to be written to the file

remove(“myFile.txt”) - deletes the specified file
-returns 0 on success; other integer on failure

rewind(fp) - resets the file position indicator back to the beginning of the file

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

What are three standard streams that all programs can use without calling fopen or fclose?

A

-stdin input from the keyboard
-stdout output to the terminal; normal program output
-stderr output to the terminal; error and warning messages

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

Where should error messages be sent and why?

A

You must ALWAYS send error messages to stderr and not stdout.

This is because they will now show as error messages in the terminal

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

How exactly does an #include statement work?

A

It will find the file after the # and copy it’s contents into the current position in the program

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

include <stdio.h></stdio.h>

What is the difference between these statements

#include “myFile.h”

A

<stdio.h>: search for this file using the path in which the pre-processor expects to find such files

"myFile.h": search for this file firstly in the same directory as this program, and then using the path in which the pre-processor expects to find such files
</stdio.h>

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

Why can using #define be dangerous

A

Definitions are substituted before the compiler compiles the source code so any errors introduced are hard to trace

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

what do these statements do?
#ifdef
#ifndef
#undef
#else
#elif
#endif

A

ifdef if a macro is defined

#ifndef if a macro is not defined
#undef undefine a macro
#else otherwise
#elif else if
#endif end of the #ifdef or #ifndef block

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

What are some strong macro conventions

A

Macro names should be all capitals

System macros should start with two underscores

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

Why might someone choose to use Macros?

A

Defining macros can make your code more readable

Defining macros are good for values that might change some time in the future

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

What are the four storage classes in C

A

Auto(default)
register
static
extern

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

What does the register storage class do?

A

Variable is stored in the CPU’s registers for quick access

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

What does the static storage class do?

A

The variable will continue to exist even after the block in which it is defined terminates
Value is retained between repeated calls to the same function
Scope is limited to the block in which it is defined
function is only visible within its translation unit(it’s file)

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

what does the extern storage class do?

A

The scope is global
The function is visible globally

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

How should we name the header (.h file)?

A

It should always be named after the code (*.c) file it belongs too

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

What are some disadvantages of C being a weakly typed language?

A

As errors are not checked at compile time there can be type mismatch errors during program execution

Unexpected behavior while executing

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

Define a function in C

A

A uniquely named group of program statements which accepts 0 or more arguments and will return 0 or 1 to the calling code

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

Note: each function in C must have a unique name

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

Define a procedure in C

A

A procedure is a function which has no return value

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

Why should functions be prototyped?

A

The (one-pass) compiler needs to know a function’s definition before it is called, and functions may appear in any order in the program module.

The functions may call each other - so there is no ordering of the function definitions that defines them before they are called

The code for the function might not be in this program module.

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

What information is needed to prototype a function and how is it done?

A

The return type, function name and parameter types are needed (parameter names are not necessary)

like:
void printArray (char []);

or

int anIntFunction ();

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

Why are global variables considered very bad practice

A

They can cause a number of issues in including:
-can make code harder to maintain and debug
-Reduced encapsulation and modularity
-Namespace pollution and conflicts

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

What are static variables?

A

They are declared using the static keyword and initialized once the function is first called. They will retain their values when they go out of scope

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

What is the lookup table and how does it work?

A

It’s used to find the data assigned to variable names, when a variable is created it’s name, type and address are assigned to the lookup table. When the variable is used the name is found in the lookup table and the memory address can be used to find the data in memory

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

Note: pointers are a base datatype

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

How can you assign the memory address of a variable to a pointer

A

Using the & character, &var is the location where var is stored

like this:

char ch = ‘A’;
char *p;

p = &ch;

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

How can a memory address be shown in a printf statement?

A

Using %p

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

How much memory does storing a pointer take?

A

8 bytes on windows 64, 3 on windows 32

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

In pointer arithmetic how many bytes are added by the statement x++

x is a pointer

A

2 bytes are added

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

char str[20] = “Hello world!”;
char *p = str;

What will this printf statement output?

printf(“p is %s\n”, p);

A

p is Hello World!

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

What is the advantage of using void pointers?

A

Void pointers can point to any datatype as long as it is cast before use

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

How could i cast a void pointer to a char?

A

*(char *)p

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

What causes these errors:

Memory fault

Segmentation fault

A

Memory fault: trying to access memory it is not allowed access to

Segmentation fault: trying to access memory in a way that is not allowed

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

What is an issue that can occur here?

char str1[20] = “Goodbye”;
char str2[6] = “Hello”;
str2[16] = ‘x’;

A

The program won’t throw any errors however the program could be corrupted as the memory address that would belong to str2[16] will be changed to x. If this is currently being used by another variable it will be corrupted

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

What are some solutions when you don’t know how much memory is needed at runtime

A

The best way is to dynamically allocate memory at runtime using pointers however we can also declare an array whose size is determined at runtime(potential issue is we don’t know how much free contiguous memory is available) or process the data in smaller dhunks

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

How could i dynamically allocate memory for an int that is 23 numbers long?

A

int *p = NULL;

p = (int )malloc(23sizeof(int));

Note: you must always trap the fact that memory was not allocated

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

What happens when a variable goes out of scope?

A

Its memory is released

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

What is a memory leak?

A

When allocated memory is not released even when it goes out of scope/ is not longer needed

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

When using malloc what must also happen?

A

The memory must be explicity freed

like:

free(p)

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

What are structures in C?

A

A type of variable that groups multiple related data items together
-The closest thing that C has to a class

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

How can i declare a structure in C?

A

struct <structure>
{
<variable>;
};</variable></structure>

This should be done before the function prototypes

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

How can new datatypes be defined using structures and the typedef command?

A

typedef struct bookStruct BOOK;

This can then be used as a datatype in variable declaration like:

BOOK myBook;

this is identical to

struct bookStruct myBook

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

What are some things that will accept a structure as a parameter

A

A function can accept a structure as a parameter as well as returning one

If you create a datatype using a structure then you can have arrays of them e.g.
BOOK books[20];

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

How can i access the parameters of a structure with and without a pointer?

A

Without a pointer:
structureName.parameterName

With a pointer e.g. BOOK *secondBook;
secondBook->parameterName

this saves the need for the structure to be de-referenced like:
(*secondBook).parameterName

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

What are some situations where a linked list would be used over an array

A

-When we don’t know how many elements the array needs to hold
-We don’t want to store the elements in a linear structure e.g. a tree
-You want to store elements of different datatypes

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

Define a linked list

A

A data structure containing an ordered sequence of nodes in which each node consists of data and one or more links to other nodes in the sequence.

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

What are some advantages of a linked list

A

It is a memory-efficient means of storing large data structures

It has a speed efficient means of inserting and deleting nodes

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

What is an advantage and two disadvantages of using arrays

A

With arrays you can go directly to the nth element

Disadvantages:
-insert delete operations require other elements to be moved
-if an element needs to be inserted into a full array then the array must be extended or the program will have to stop

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

How can i define the structure of a list node and initialize an empty list?

A

struct anode
{

/*this is where the data variables go e.g. */
char data;
 struct anode *nextNode };

typedef struct anode NODE;

NODE *root = NULL;

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

How can i allocate memory and add a node to a linked list?

A

Initialise the node:
NODE *newNode;

Allocate Memory:

if ( ( newNode = (NODE *)malloc(sizeof(NODE)) ) == NULL)
{ …}

Then set the nodes new values:

newNode->data = ‘A’;
newNode->nextNode = NULL;

then add it to the empty list:
root = newNode;

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

How do i add a new node to the beginning of a linked list

A

newNode->nextNode = root;
root = newNode;

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

How do i add a new node to the end of a linked list

A

root->nextNode = newNode;

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

How should i add a node in the middle of a linked list

A

-Find the right place to insert
-Link the new node to the tail of the list
-Link the head of the list to the new node

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

Should linked list nodes be in contiguous memory?

A

There is no need for linked nodes to be in contiguous memory

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

What are some advantages of linked lists?

A

Does not matter where each node is stored in memory
insert/delete requires only changing the values of 1/2 pointers
Size of linked list is limited only by computer memory
Lists may be linked in more than one way

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

What are some disadvantages of linked lists

A

To find an element you must start from the beginning and follow the pointer

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

What is the wrong way to insert a node to a linked list?

A

If we first link the head of the list to the new node then we have no idea how to link the tail node to the end of the list and all subsequent items in the list are lost

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

What must we also do for each deleted node

A

We must also free the memory for each node

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

What is a doubly linked list and why is it useful?

A

It’s where nodes in the list are linked in two distinct orders, for example one order could be alphabetical and one could be chronological

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

What are 4 common types of dynamically linked data structures

A

-Stacks
-queues
-circular lists
-trees

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

What is POSIX?

A

It is a family of related standards used for maintaining compatability between variants of UNIX

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

What does POSIX define?

A

It defines:
-application programming interface (API)
-command line shells
-utility interfaces

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

What set of services does POSIX describe?

A

It describes:
-an interface, written in C
-a command interpreter
-common utility programs
-standard semantics and syntax

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

What is the open group and when was it founded?

A

Established in 1995
It aims to create a single UNIX specification to ensure compatibility across platforms
-918 members in total

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

What are the fully certified varieties of UNIX?

A

Hewlett Packars: HP-UX
IBM: AIX
Apple: MacOS X

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

What are the mostly compliant varieties of UNIX?

A

most Linux distributions
Android
Cygwin(TF?)

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

What are the three layers UNIX is made up of?

A

The kernel
The shell
The program / application layer

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

What is telnet and some properties about it?

A

A virtual terminal connection
-application layer protocol over internet or local area network
-interactive text oriented communication
-unencrypted

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

What is ssh

A

It’s an encrypted version of telnet

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

What are the standard 3 unix editors and some of their properties

A

vi - specified in POSIX standard; lightweight
ed - line editor; very lightweight
emacs - incredibly flexible (and complicated); heavyweight

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

What editor should i use if i want speed and what editor should i use if i want flexibility?

A

vi for speed
emacs for flexibility

114
Q

What will these commands, related to environment variables, do:
echo $PATH

printenv

export ECM2433=~/ecm2433
cd $ECM2433

export PS1=”hostname $ “

A

Show the value of the variable called PATH
Show the values of all defined variables
Set the value of the variable called ECM2433(~/ is the current user’s home directory)
Set the command line prompt to the name of the current server

115
Q

What is everything in UNIX either?

A

Everything in UNIX is either a file or a process
A file is passive e.g. program code
a process is active e.g. running program

116
Q

What does every process have?

A

-Unique PID(process identifier)
-Exactly one parent process (apart from the system swapper which has PID 0)
-Zero or more children
-A child is spawned when the system fork command is called

117
Q

What do these UNIX process commands do:
ps
top
&
jobs
bg
fg
kill
nohup
nice
renice

A

ps process snapshot
top real-time list of processes
& run process in the background
jobs list of the background child processes of current process
bg put a paused job into the background
fg bring a background job into the foreground
kill kill a process
nohup keep a child process running even when the parent process nishes
nice lower the priority of a child process as you spawn it
renice lower the priority of a current process

118
Q

What do these UNIX redirection commands do?
|
>
<

A

| pipe
> redirect stdout to a new file
< redirect stdin from a file

119
Q

What will this UNIX command do?
ps -ef | grep -i matlab

A

Show all processes whose command line includes the text “matlab”, ignoring case

-e select all processes
-f full-format listing
-i ignore case

120
Q

What will this UNIX command do?
ps –efH

A

Show the parent/child hierarchy of all processes
-e select all processes
-f full-format listing
-H show process hierarchy

121
Q

What can be used to show the parent/child hierarchy of all processes?

A

The top command

122
Q

What is the difference between foreground and background in UNIX

A

foreground:
- your session waits until the process has finished
background:
- you can continue entering commands while the process runs
- the process is killed if the parent process finishes

123
Q

What command can i use to run a program in the background

A

programName &

124
Q

What are the two ways we can force a process to finish

A

using the job number like:
$jobs -l
[1] + 18561 running tempsleep
$kill %1

using the PID like:
$jobs -l
[1] + 18561 running tempsleep
$kill 18561

125
Q

How can i enable a child process to continue running when I log out?

A

$ nohup tempsleep &

126
Q

Which programs should run with higher priority than others?

A

Background processes should always run at a lower priority than foreground processes e.g.
$ nohup nice tempsleep &
$ renice -p <PID></PID>

127
Q

i have this program called tempsleep.c
int main ()
{
sleep(60);
return 0;
}

how can i run it in the foreground and how can i run it in the background?

A

foreground:
$tempsleep
background
$nice tempsleep

128
Q

How can i fork a process then check to see if the fork was successful?

A

include <stdio.h></stdio.h>

#include <unistd.h></unistd.h>

int main ()
{
int pid = fork(); //fork the process

if ( pid < 0 ) //If the fork fails it returns -1
{ fprintf(stderr,”Fork failed.\n”);
return 1;
}
else if ( pid == 0 ) //the child process will always have pid of 0
{ /* the child process / }
else
{ /
the parent process */ }
return 0;
}

129
Q

What does the fork command do?

A

It will create a duplicate of the parent process and run it

130
Q

What do these functions do:

getpid()
getppid()

A

Will get the PID of the current process
Will get the PID of the parent process

131
Q

What will this line do?
wpid = (int)waitpid(pid,&status,0);

A

The parent process will wait for a specific child process belonging to pid to finish

132
Q

What will this line do?
wpid = (int)waitpid(0,&status,0);

A

The parent process will wait for any child process to finish

133
Q

What does execve() do?

A

It will replace the current process with a new process, by default the process is replaced by a new version of itself however a different process can be specified like:
execve(“filepath”, arguments, environment variables)

134
Q

What are the three ways of communicating between processes and how do they work?

A

signals:
-need to know the PID of the process you are signalling
-no data can be transferred
-the receiving process does not need to keep checking

files:
-one process writes a file, the other reads it (need to consider file -locking)
-data can be transferred
-receiving process has to keep checking

pipes:
-each process opens one end of a unidirectional “pipe” down which data is sent
-the processes must be parent & child, or siblings
-data can be transferred
-receiving process has to keep checking

135
Q

At what point should a pipe used for process communication be opened and what is the code to open a pipe?

A

It must be opened before the fork so that the parent and child can share it
code:

int childpid;
int fd[2];

if ( pipe(fd) )
{ /* an error occurred */ }

childpid = fork();

**Important Note: in this code fd is a file descriptor array that will be populated by the pipe function, fd[0] would hold the file descriptor for reading from the pipe and fd[1] would hold the file descriptor for writing to the pipe.

136
Q

What must be done whenever a process wants to send or receive information along a pipe?

A

The opposite side of the pipe must be closed to avoid unexpected behavior, like:

}
/* child process closes up input side of pipe /
close(fd[0]);
/
Send “str” through the output side of pipe */
write(fd[1], str, (strlen(str)+1));
}

137
Q

Is fd[0] the input side of a pipe or the output side of a pipe

A

It’s the input side of a pipe, from which the process will receive data

138
Q

What is the code for a process to read and write to a pipe

A

Read:
{ char str[] = “Hello Mum!”;
/* child process closes up input side of pipe /
close(fd[0]);
/
Send “str” through the output side of pipe */
write(fd[1], str, (strlen(str)+1));
}

Write:

{ char buffer[80];
int numBytes;
/* parent process closes up output side of pipe /
close(fd[1]);
/
Read a string from the input side of the pipe */
numBytes = read(fd[0], buffer, sizeof(buffer));
printf(“Parent received string: %s (%d bytes)\n”,
buffer, numBytes);
}

139
Q

What does the kill command do and how does it work?

A

The kill command enables you to terminate a long-running background process:

either by specifying the process number:
$ kill %1
or the PID:
$ kill 10748

What the kill command is actually doing is sending a signal to the process.
The command
$ kill 10748
is actually the equivalent of
$ kill –TERM 10748
which is sending the SIGTERM signal (please terminate) to the process

140
Q

How can i have my program respond to a specific signal?

A

note:signal.h must be included
#include <stdio.h>
#include <stdlib.h>
#include <signal.h></signal.h></stdlib.h></stdio.h>

void sig_handler (int signo)
{
if (signo == SIGUSR1)
{
printf(“received SIGUSR1\n”);
if ( signal(SIGUSR1,sig_handler) == SIG_ERR )
printf(“\ncan’t catch SIGUSR1\n”);
}
}

int main ()
{
if ( signal(SIGUSR1,sig_handler) == SIG_ERR )
printf(“\ncan’t catch SIGUSR1\n”);

while(1)
sleep(1);
return 0;

141
Q

Linux is a multi-tasking operating system, what does that mean?
(4 statements)

A

Each process runs in its own lump of memory - its virtual address space

Each virtual address space starts at memory address zero

The operating system maps virtual memory addresses to real, physical memory addresses using page tables

The virtual address space is usually contiguousin some other operating systems it may be segmented

142
Q

What are some things that are good about virtual memory addressing(6 in total)

A

Transparency
-processes are unaware of virtualisation

Protection and isolation
-one process cannot interfere with another

Flexible memory placement
-operating system can move things around in memory

Shared memory and memory mapped files
-efficient interprocess communication
-shared code segments, i.e. dynamic libraries

Dynamic memory allocation
-grow memory usage on demand

Paging
-creates the illusion of near-infinite memory

143
Q

What is the virtual address space made up of from the top down and a basic overview

A

The kernal
Stack - auto variables
libraries - idt this is important
Heap - dynamically allocated memory (via malloc)
BSS - uninitialised static variables
Data - initialized static variables
Text - program machine code and constraints

144
Q

In the virtual memory stack what are the two pointers that must always exist

A

bp(fp) or base(frame) pointer - this will always point to the top of the current frame of virtual memory
sp or stack pointer - this will point to the end of the current frame of virtual memory

145
Q

What exists inside a stack frame?

A

The return address
Address of the previous base (frame) pointer
function parameters
initialized variables

146
Q

How is fragmentation in the heap caused and how can it be avoided?

A

It’s caused by frequent memory allocation and deallocation, memory on the heap becomes divided into small non-contiguous blocks over time

147
Q

What does the state of an executing program depend on?

A

Virtual address space:
-code: the executing program code
-data/BSS: static variables
-stack: function return address, parameters, auto variables
-heap: dynamically allocated variables

Registers, including:
-sp: stack pointer
-bp: base pointer
-pc: program counter

148
Q

What does setjmp do?

A

include <stdio.h></stdio.h>

It will store the contents of the registers to a buffer, like:

#include <setjmp.h>
int main ()
{
jmp_buf mainbuf;
if ( setjmp(mainbuf) == 0 )
printf("register contents stored\n");
return 0;
}</setjmp.h>

149
Q

What does longjmp do?

A

include <stdio.h></stdio.h>

It will restore the contents of the registers from a buffer, like:

#include <setjmp.h>
int main ()
{
jmp_buf mainbuf;
int setValue;
setValue = setjmp(mainbuf);
printf("setValue = %d\n", setValue);
if ( setValue != 0 )
return 0;
longjmp(mainbuf,2);
printf("after longjmp\n");
return 0;
}</setjmp.h>

150
Q

Why might setjmp() and longjmp() be used in a program

A

They can be used to return the program to an earlier state in its execution, when setjmp() is used the entire program state is saved and when longjmp() is called the state returns to how it was when setjmp() was called. The program will then continue execution back at the setjmp() statement

151
Q

What is a subroutine?

A

Also known as procedures and functions are used to encapsulate a sequence of instructions for a specific task

152
Q

What is a coroutine

A

Coroutines are a generalisation of subroutines that allow for suspended execution

153
Q

What is the difference between concurrency and parallelism?

A

Concurrency:
-multiple processes accessing one disk
-multiple processes sharing one CPU
-time slicing
-context switching

Parallelism:
-Multiple processes running on separate CPU’s

154
Q

Give one example usage of coroutines and why they are used

A

Coroutines are used are in computer games to maintain a high framerate because:

-You have a computationally heavy routine that needs to run
-You do not want that entire routine to run within one frame
-It would impact the frame rate and make the gameplay look jerky
-Coroutines can split the computationally heavy single routine whilst yielding “time” back to the game loop, thereby keeping the frame rate stable
-The program switches between the coroutine and the game loop

So coroutines allow the computationally heavy routine to be split across multiple frames rather than requiring it to finish in one.

155
Q

Note: in the memory jumps lecture it might be worth figuring out the setjmp/longjmp couroutines program, time allowing

A
156
Q

How do couroutines work with the stack?

A

Stack pointers will simply move to the function being yielded too and then will move back after

157
Q

With machine code what is the ELF

A

The ELF (Executable and Linkable Format) header tells Linux how to create a new process
(there is a full table on what each of the 31 bytes does but surely this won’t come up)

158
Q

What does C++ add onto C?

A

Classes
exception handling
function and operator overloading
default values for parameters
pass by reference

159
Q

What standard of C++ are we using?

A

C++11

160
Q

How can i write a print statement in C++?

A

include <stdio.h></stdio.h>

#include <iostream></iostream>

int main()
{
std::cout &laquo_space;“Hello world!” &laquo_space;std::endl;
return 0;
}

If we want to avoid having to write the scope resolution operator (std::) we can write a statement like this:

#include <iostream>
using namespace std;</iostream>

int main()
{
cout &laquo_space;“Hello world!” &laquo_space;endl;
return 0;
}

161
Q

In C++ where does cout go and where does cerr go?

A

cout goes to stdout
cerr goes to stderr

162
Q

In C++ what does endl do?

A

prints a newline and flushes the output buffer

163
Q

include <iostream></iostream>

What will this line of code output in C++?

#include <iomanip>
using namespace std;</iomanip>

int main()
{
int aNum = 42;

cout &laquo_space;setfill(‘*’) &laquo_space;setw(10) &laquo_space;aNum &laquo_space;”;” &laquo_space;aNum &laquo_space;endl;

return 0;
}

A

This code will output “**42;42”

164
Q

Note: we can take standard C object code and we can link it into C++

A
165
Q

How can we perform function overloading in C++

A

Function overloading in C++ is very easy, to perform it the two different functions must have different numbers or types of parameters, they may also have different return types, like:

int myabs (int i)
{
if ( i<0 )
return -i;
else
return i;
}
float myabs (float f)
{
if ( f<0.0 )
return -f;
else
return f;
}

166
Q

How does class declaration work in C++?

A

define SIZE 100

Quite similar to other languages, like this:

// Define the Stack class
class Stack
{
int stck[SIZE]; //These are the private class variables
int index;
public:
void push(int); //These will be public member function
prototypes
int pop(void);
};

167
Q

What is a public member function prototype?

A

A declaration of a function belonging to a class and is accessible from outside the class. Like any other function prototype it specifies the functions name, return type and param list without it’s implementation.

168
Q

What are the three access specifiers in C++

A

private(default)
-can only be accessed within the class
public
-can be accessed by any part of the program
protected
-Can be accessed by member functions of the class they are declared it
-Can also be accessed by member functions of classes derived from the original class, allowing for inheritance

169
Q

How can i use classes in C++

A

include<Stack.hpp></Stack.hpp>

To import the class we must include the class hpp file:

Then we can use a constructor to create a reference to the class which can then be used to access the class functions, like:

int main ()
{
Stack s1; //This is the class constructor function
int value;

s1.push(23);
s1.push(1);
value = s1.pop();

return 0;
}

This could be an example of the Stack.hpp file:

// Define the Stack class
class Stack
{
int stck[SIZE];
int index;
public:
void push(int);
int pop(void);
};

170
Q

What are constructor and Destructor classes in C++

A

Constructor classes:
-A constructor is a special member function that gets called automatically when an object of the class is created.
-It has the same name as the class.
-If you don’t provide a constructor explicitly, C++ provides a default constructor, which initializes the member variables to default values (e.g., 0 for numeric types, nullptr for pointers).

Destructor classes:
-A destructor is also a special member function that gets called automatically when an object goes out of scope or is explicitly deleted.
-It has the same name as the class preceded by a tilde (~).
-Primarily used to release resources used by the object

171
Q

How can we create parameterised constructors in C++

A

Very similar to in other OOP languages, we can add the parameterized constructors after the class definition like:

class NewClass
{
int a,b;
public:
NewClass(int,int); // parameterised constructor
};

NewClass::NewClass(int i, int j)
{
a = i;
b = j;
}

172
Q

How can i add functions to my classes in C++

A

We have to first prototype it in the class definition and then we can define it after, like:

class NewClass
{
int a,b;
public:
void showValues();
};

void NewClass::showValues ()
{
cout &laquo_space;“a=” &laquo_space;a;
cout &laquo_space;”, b=” &laquo_space;b &laquo_space;endl;
}

173
Q

How can we overload parameterised constructors in C++?

A

We simply have to have a differing number of arguments for each constructor, for example:

NewClass::NewClass(int i, int j)
{
a = i;
b = j;
}

NewClass::NewClass(int i)
{
a = i;
b = 0;
}

174
Q

How do default values work with parameterised constructors?

A

We can add default values to our parameterised constructors which will take effect if the value is not specified when it’s called. Keep in mind that only trailing values can be defaulted with the exception of when all values are defaulted. For example we can declare:

NewClass::NewClass(int i, int j=0)
{
a = i;
b = j;
}

Then if we call this like:
NewClass nc(3)

then the value of a will be 2 and the value of b will be defaulted to 0

175
Q

How can i create an uninitialized int pointer in C++? How can i create it initialized and how can i create a pointer to an array?

A

To create an uninitialised pointer

int *p = new int;

To create an initialised pointer:

int *p = new int(23);

To create a pointer to an array of 25 integers:

int *p = new int[25];

176
Q

How can I free pointers in C++?

A

for a standard pointer
delete p;

for an array pointer
delete[] p;

177
Q

How can i create a pointer to a initialised/unitialised class in C++? How can i create an array of these?

A

a single MyClass, uninitialised
MyClass *c = new MyClass;

a single MyClass, initialised with value 43
MyClass *c = new MyClass(43);

an array of 25 MyClass’es
MyClass *c = new MyClass[25];

note: freeing these pointers is the same as normal

178
Q

What is the difference between creating and freeing pointers belonging to a class in C and C++

A

C will allocate and free memory like it does with any other pointer

When creating a pointerC++ will allocate memory first and then call the constructor

When freeing a pointer C++ will call the destructor then deallocate memory

179
Q

How can i do pass by value, pseudo pass by reference and pass by reference in C++

A

Pass by value:

void addTen (int x)
{
x+=10;
}

pseudo pass by reference (This requires a pointer to be passed to the function:

void addTen (int *x)
{
*x+=10;
}

Pass by reference:

void addTen (int &x)
{
x+=10;
}

180
Q

What is a reference and how is a variable affected when it’s reference is changed?

A

A reference is an alias for a variable

When a reference is changed the vairiable changes to match it

181
Q

What is a copy constructor?

A

It’s a member function that initializes an object using another object of the same class

182
Q

What are static member variables?

A

They are shared by all objects of the same class
They can be accessed even if no objects exist

183
Q

What is multiple inheritence in C++?

A

It’s where a class can inherit properties and behaviors from more than one base class, allowing the combining of functionality of multiple classes

184
Q

What is the general form for class inheritance in C++

A

General form:

class derived-class-name: access specifier base-class-name
{ //class body}

for example:

class MySpecialString: public MyString
{
char type;
public:
MySpecialString(char, const char *);
};

185
Q

What is a friend function in relation to a class?

A

In relation to a class, a friend function is:
a non-member function
i.e. a function that is not a member of the class
which has access to the private and protected elements of the class
i.e. the class for which it is a friend

186
Q

What are two things that friendship(friend functions) is not?

A

-Inherited: e.g friends’ children are not your friends
-Transitive: a friend of you friend is not your friend

187
Q

How can i declare a friend function in a class?

A

Using the key word friend in the class prototyping, like:

class MyClass
{
int a,b;
public:
MyClass(int, int);
friend int sum(MyClass);
};

MyClass::MyClass (int i, int j)
{
a = i;
b = j;
}

int sum (MyClass x)
{
return x.a + x.b;
}

This friend function takes a constructed class as an argument

188
Q

How can we create a friend function that’s a member of another class?

A

I dont really understand but like this:

class MyOtherClass; // forward reference; a sort of “class prototype”

class MyClass
{
int a,b;
public:
friend int MyOtherClass::sum(MyClass);
void setab(int, int);
};

class MyOtherClass
{
int c;
public:
int sum(MyClass);
};
int MyOtherClass::sum (MyClass x) {…}

189
Q

What is one specific use of friend fucntions?

A

One specific use of friend functions is in relation to operator overloading

190
Q

What is operator overloading in C++

A

It’s a feature that allows you to redefine the behavior of existing operators for user-defined types (like classes and structs). This means you can make these operators work with your custom data types in a way that mimics how they work with built-in types like integers or strings.

for example: the + operator working with complex numbers

191
Q

What is the aim of operator overloading

A

The aim of operator overloading it to make life easier for users of a class, not for the developer of the class.

Easier means:
easier to understand the code
fewer code defects

192
Q

What operators cannot be overloaded?

A

.
sizeof
?:
::
.*

193
Q

How can we implement operator overloading for two custom datatypes?

A

class MyInteger
{
int i;
public:
MyInteger (int i) { this->i = i; }

  int   operator+(MyInteger); };

// This function represents <MyInteger> + <MyInteger>
int MyInteger::operator+ (MyInteger m)
{
return this->i + m.i;
}</MyInteger></MyInteger>

194
Q

How can we implement operator overloading for a custom datatype and a non custom datatype

A

class MyInteger
{
int i;
public:
MyInteger (int i) { this->i = i; }
int operator+(int);
};

// This function represents <MyInteger> + <int>
int MyInteger::operator+ (int a)
{
return this->i + a;
}</int></MyInteger>

195
Q

Why might we use a friend function in operator overloading?

A

When we want to add a non custom datatype with a custom datatype, e.g. int+myInt

like:

class MyInteger
{
int i;
public:
MyInteger (int i) { this->i = i; }

  friend int operator+(int, MyInteger); };

// This function represents <int> + <MyInteger>
int operator+ (int a, MyInteger m)
{
return a + m.i;
}</MyInteger></int>

196
Q

What are two considerations when using operator overloading

A

At least one of the operands of an overloaded operator must be of a user-defined type (usually this is a class).

Overloaded operators are just function calls, so cannot preserve
-associativity e.g. 4 + 3 + 1 = (4 + 3) + 1 = 4 + (3 + 1)
-precedence rules e.g. 4 + 3 * 1 = 4 + (3 * 1) ≠ (4 + 3) * 1
of the operator, according to its built-in semantics.

197
Q

What are some plauasible examples for operator overloading?

A

myString + yourString might concatenate two std::string objects
myDate++ might increment a Date object by 1 day
a[i] might access the ith element of a MyArray object
m(i,j) might access element in row i, column j of a MyMatrix object
matrix1 * matrix2 might perform matrix multiplication on two MyMatrix objects

198
Q

What is the difference between [] and () for subscripting?

A

[] allows only one index
e.g. array[4]
() allows multiple indices
e.g. matrix(5,1)

199
Q

What operator would have to be overloaded to output a date in a custom format?

A

The &laquo_space;operator found in cout statements

200
Q

How can the &laquo_space;operator be overloaded?

A

Like this:

class MyDate
{
int year;
unsigned int month;
unsigned int day;
public:
MyDate(unsigned int,unsigned int,int);
friend ostream &operator«(ostream &os, MyDate &dt);
}

ostream &operator«(ostream &os, MyDate &dt)
{
os &laquo_space;dt.day &laquo_space;’/’ &laquo_space;dt.month &laquo_space;’/’ &laquo_space;dt.year;
return os;
}

201
Q

What is a function template?

A

It’s instructions for how to build a family of similar looking functions

202
Q

How can we implement a function template?

A

Using the line “template<dataname>" infront of a function and then replacing any datatypes in the function with T, like:</dataname>

template<dataname>
void myswap (T &x, T &y)
{
T temp = x;
x = y;
y = temp;
}</dataname>

203
Q

What is a class template and how can it be implemented?

A

It’s similar to a function template, it allows the building of a family of similar looking classes. It works in the same was as function templates like:

template<typename>
class Stack
{
T stck[SIZE];
int index;
public:
static int count;
Stack();
Stack(Stack &);
~Stack();
void push(T);
T pop(void);
};</typename>

204
Q

Which data structures are so widely used that C++ provides a set of standard templates?

A

stacks
queues

205
Q

What are the four main components in the standard template library(STL)?

A

Containers
-vectors, queues, stack
Iterators
-objects that enable a program to traverse a container
Algorithms
-e.g. binary search
functions

206
Q

What can exceptions do in C++?

A

-enable error trapping
-allow the transfer of program execution to another part of the code
-during execution of the program, i.e. at runtime

They can be thrown automatically(e.g. divide by zero) or programmatically

207
Q

How can i throw integer exceptions in C++?

How can i throw character exceptions in C++?

A

throw 20;

This will throw exception number 20

208
Q

How can i catch these types of exceptions in C++:
Integer exception
char exception
Catch-all exception

A

catch (int e) { printf(“Integer exception %d\n”,e); }
catch (char e) { printf(“Character exception %e\n”,e); }
catch (…) { printf(“Catch-all exception\n”); }

Note: a char catch can only catch char exceptions, same for integer exceptions

209
Q

What happens if an uncaught exception is thrown?

A

This will output:
terminate called after throwing an instance of […]
Abort(coredump)

210
Q

How can we limit the type of exception a function might throw?

A

In the function declaration we can specify the types like:
int myFunction(int i) throw (int,float);

If myFunction throws an exception of a different type the program will terminate, abort(coredump)

211
Q

in C++ what do these function declarations mean for the exceptions that can be thrown?

int myFunction (int i) throw();

int myFunction (int i);

A

With the first declaration no exceptions are allowed to be thrown

With the second all exceptions are allowed to be thrown

212
Q

What are exception objects in C++

A

They are instantiated from an exception object class and can be thrown like normal exceptions. They provide a mechanism for handling runtime errors and allow the program to continue execution where a normal exception might have stopped

213
Q

How can i define exception objects in C++?

A

First we must include exceptions like,
#include <exception></exception>

then we create an exception class that specifies what processing should occur, like:

class MyException: public std::exception
{
virtual const char *what() const throw()
{
return “My exception happened”;
}
}

Note if we want to use this exception it must be instantiated

214
Q

How can i throw and catch exception objects in C++

A

To throw one it must first be instantiated from a class, then it can be thrown like any other numerical exception.

throw myex;

to catch one we need to make use of the exception import, we can do it like:

catch ( std::exception &e)
{
std::cout &laquo_space;e.what() &laquo_space;std::endl;
}

the line e.what() will output the message that goes with the exception object

215
Q

What causes these standard exceptions from the C++ standard library:
bad_alloc
bad_cast
bad_exception
bad_typeid
ios_base::failure

A

thrown by failure to allocate memory
thrown by dynamic casts
thrown when an exception type does not match any cast
thrown by the typeid operator
thrown by functions in the iostream library

216
Q

How can we use standard exceptions?

A

in a standard catch statement like:

catch (bad_alloc &b)

217
Q

How can we determine the type of an object or variable at runtime

A

using typeid()

typeid(MyClass).name()

218
Q

What are the 4 standard streams in C++?

A

cin - standard input (stdin in C)
cout - standard output (stdout in C)
cerr - standard error output (stderr in C)
clog - buffered version on cerr

219
Q

What are these operators
»
«

A

> > is the extraction operator because it extracts characters from a stream

&laquo_space;is the insertion operator because it inserts characters into a stream

220
Q

what are the three stream classes in C++ and what access do they have?

A

ifstream - read access
ofstream - write access
fstream - read/write access

221
Q

How do i open a file in C++?

A

f.open(<filename>, <mode>)</mode></filename>

example:
fstream outFile;
outFile.open(“example.bin”, ios::out | ios::app | ios::binary);

222
Q

What do the following file mode flags do in C++?
ios::in
ios::out
ios::binary
ios::ate
ios::app
ios::trunc

A

read
write
binary mode
set initil position to end of file
append
if file opened for output and file already exists then overwrite

223
Q

How do i open and close file streams in C++?

A

include <fstream></fstream>

ifstream inFile;
ofstream outFile;

inFile.open(“myFile.txt”); // ifstream: default mode is ios::in
outFile.open(“myFile2.txt”); // ofstream: default mode is ios::out

if ( !inFile.is_open() || !outFile.is_open() )
// do some error processing

inFile.close();
outFile.close();

224
Q

How can i write to a file in C++?

A

ofstream out(“myFile.txt”); // open normal output file

if ( !out.is_open() )
{ /* error processing */ }

out &laquo_space;“Sam “ &laquo_space;1.78 &laquo_space;endl;
out &laquo_space;“Chris “ &laquo_space;1.64 &laquo_space;endl;
out &laquo_space;“Lindsay “ &laquo_space;1.69 &laquo_space;endl;

out.close();

225
Q

How can i read from a file in C++?

A

ifstream in(“myFile.txt”); // open normal input file
char name[20];
float height;

if ( !in.is_open() )
{ /* error processing */ }

in&raquo_space; name&raquo_space; height;
while ( !in.eof() )
{
cout &laquo_space;“name: “ &laquo_space;name &laquo_space;”, height: “ &laquo_space;height «endl;
in&raquo_space; name&raquo_space; height;
}

226
Q

In C++ file streams what does ignore() do?

A

Reads and discards characters until either
-certain number of characters have been ignored (1 by default) or
-the character specified by delim is encountered (EOF by default).

used like:

ifstream in(“test.txt”);

if ( in.is_open )
{
// ignore up to 10 characters, or until the first space
in.ignore(10, ‘ ‘);
}

227
Q

What do these stream state flags do
bad(0
fail()
eof()
good()
clear()

A

Returns true if a reading or writing operation fails
e.g. try to read from a file that is not open for reading, or try to write to a full disk

Returns true in the same cases as bad(), but also when a format error happens
e.g. try to read an integer value and get an alphabetical character

Returns true if a file open for reading has reached the end

Returns false where any of the above return true
NB: not the opposite of bad()

Resets the state flags

228
Q

What is big endian and what is little endian?

A

big endian: most significant (“biggest”) digit first
little endian: least significant (“littlest”) digit first

for example:
Decimal number:
123 = 100 + 20 + 3

Little endian decimal number would be:
321 = 3 + 20 + 100

229
Q

How can we create a program that can tell whether or not a system is big or little endian?

A

In C++ we can create a program to exploit how memory addresses are assigned.

We create an integer x with the value 1 and cast a character pointer to memory address of x.
If the character pointer is 0 then the system will store the most significant byte (in this case 0) first and is big endian
If the character pointer is 1 then the system will store the lease significant byte (in this case 1) first and is little endian

230
Q

What do bit fields do?

A

Bit fiends allow you to address smaller units of memory than one byte

231
Q

How can i create a structure that has bit fields

A

After the variable name we must add : 1 where 1 is the number of bits the variable will take up, like:

struct textflags
{
unsigned char bold : 1;
unsigned char italic : 1;
unsigned char underline : 1;
};

struct textflags mytext;
mytext.bold = 1;
mytext.italic = 0;
mytext.underline = 1;

232
Q

What are unions in C++ and when might i want to use them

A

A union is a user-defined data type that allows you to store different data types within the same memory location. However, only one member of the union can hold a value at any given time. Assigning a value to one member effectively overwrites the value in any other member.

We might want to use unions when:

When you have data that doesn’t need to be stored simultaneously, unions can save memory.

Since unions can only hold one value that means that we can change two values by writing one variable

233
Q

How is little endian useful for C programs?

A

It allows easier implicit type conversion, if the system wasn’t little endian then pointer arithmetic would have to be performed to convert types

(This was wierdly explained in the lecture ngl, i dont get it)

234
Q

What is the bitwise operation for multiplication and division?

A

left shift by 1 is multiplication by 2, right shift by 1 is division by 2

235
Q

When setting a bit what does this code do?

x |= (1 &laquo_space;5)

A

it will set the 6th bit of x to 1

00100000

236
Q

What does the const modifier do for the following:
variable
pointer to const variabile
constant pointer to a variable
constant pointer to constant variable

A

variable’s value cannot be changed after initialisation

the thing being pointed to cannot be changed

cannot change the pointer, but can change the value it is pointing to

neither pointer nor thing pointed to can change

237
Q

What are enumerations in C++?

A

It’s a set of user-defined(named) integral constants
for example instead of representing days of the week as integers 0 - 6 we can define them as meaningful names, like:
enum dayofweek { Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday };

238
Q

What is a variadic function?

A

It’s a function that can accept a variable number of parameters, e.g. a printf statement

239
Q

This is an example of a variadic function

A

include <stdarg.h></stdarg.h>

void myprintf (char , …); / function prototype */
void myprintf (char *p_format, … )
{
va_list ap;
char msg[350];
va_start(ap, p_format);
vsprintf(msg, p_format, ap);
va_end(ap);
printf(msg);
}

240
Q

What is objective C?

A

It’s essentially C with objects and is a strict superset of C

241
Q

What are the two object oriented frameworks for objective C

A

Foundation: classes for basic data structures and for interacting with operating system

AppKit: classes for developing applications, windows, buttons, etc

Foundation + AppKit = Cocoa

242
Q

What are the three stages of an objective C program

A

Class instantiation
Class implementation
object instantiation and method calling

243
Q

How can i write hello world in obj C?

A

import <Foundation/Foundation.h>

int main ()
{
NSLog(@”Hello world!\n”);
printf(“%s\n”, [@”Hello world!\n” UTF8String]);

return 0;
}

244
Q

In Obj C how is #import different to #include

A

Import does not need any guard statements as it has an added feature that ensures the include code only appears once

245
Q

How can i call a message in obj C

A

Objective-C messaging:

MyObject *obj = [MyObject new];
[obj callWith:parameter1 and:parameter2];

246
Q

In obj C where is memory for objects held and what must all objects be?

A

Always in the heap and all objects must be pointers

247
Q

How can i declare an object in obj C?

How can i declare an object and allocate memory to the pointer in obj C

A

NSNumber *num1;

NSNumber *num2 = [NSNumber alloc];

248
Q

How can i declare an object, allocate memory to the pointer in obj C?

How can i declare an object, allocate memory to the pointer and initialise the value from an integer

A

NSNumber *num3a = [[NSNumber alloc] init];

NSNumber *num4 = [[NSNumber alloc] initWithInteger:43];

249
Q

How can i create new objects in obj C with literal syntax?

A

BOOL b = YES;
NSNumber *num1 = @43;
NSNumber *num2 = @’A’;
NSNumber *num3 = @91.6;
NSNumber *num4 = @b;

250
Q

how can literal syntax be used to initialise strings?

A

NSString *string = @”Hello World!”;
NSLog(@”Hello World!”);

251
Q

How can an array of objects be created with and without literal syntax in obj C?

A

Without literal syntax:
NSArray *numbers
= [[NSArray alloc] arrayWithObjects : @”one”,
@”two”,
@”three”, nil];

With literal syntax:
NSArray *numbers = @[@”one”, @”two”, @”three”];

252
Q

Note: in obj C each class will have it’s own header file

A
253
Q

How can we define and implement a new class in obj C

A

header file: MyClass.h

<import>
@interface <classname> : <superclass>
{
<attribute>
}
<method>
@end

implementation file: MyClass.m
<import>
@implementation <classname>
<method>
@end
</method></classname></import></method></attribute></superclass></classname></import>

254
Q

note: all methods are public in objective C

A

This is the format:
(void)setFirstName:(NSString *)name;

255
Q

How can i declare a method in objective C?

A
256
Q

A class, person, has a method setFirstName which looks like this
(void)setFirstName:(NSString *)name

How can i call this method?

A

Person *me;
[me setFirstName:@”Jacq”];

257
Q

How can i call two methods at a time in obj C?

A

Person *me;
[me setFirstName:@”Jacq” andLastName:@”Christmas”];

258
Q

What is the difference between instance and class methods in obj C

A

Instance methods operate on specific instances of a class and require an object to be created, are declared with a - sign before method name

Class methods are associated with the class itself and not a particular object and is called directly with the class name. Declared with a + sign before method name

259
Q

Note: a class method cannot access attributes in obj C

A
260
Q

How can we use constructors in objective C?

A

method name always starts with init
called after alloc

like:

NSNumber *anum = [[NSNumber alloc] initWithInteger:@43];
NSNumber *pi = [[NSNumber alloc] initWithFloat:@3.14159];

261
Q

What is an interface(.h file) in objective C

A

It will define what an object of a class can do
An interface is where the properties and methods of the objects are declared( prototypes)
begins with @interface and ends with @end

262
Q

What is an implementation(.m file) in objective C?

A

An implementation contains the actual code that fulfills the prototype functionalities defined in the interface

263
Q

What is a superclass in objective C?

A

A superclass is a class that serves as a blueprint for other classes. It defines a set of properties and methods that can be inherited by its subclasses.
A subclass is a class that inherits properties and methods from a superclass. It can also add its own unique properties and methods, specializing the functionality provided by the superclass.

-promotes code reusability
-promotes code organisation and polymorphism

264
Q

How can we create a constructor in objective C?

A

Create an init instance method in the interface, like:

@interface Money : NSObject
{
NSString *currency;
float value;
}
- (id) init;
@end

Then in the implementation file we need to call the superclass’s initializer like

self = [super init];

then check it was successful before assigning values to the new object, like:

if (self) {
currency = @”GBP”;
}
return self
@end

265
Q

What is the id dataype in objective C?

A

It’s a datatype that is a pointer to any type of object, essentially objective C’s version of a void pointer.
It supports dynamic referencing
As a convention used as a return type to a constructor

266
Q

What is dynamic referencing as opposed to static referencing ?

A

static referencing: object type defined at compile time
dynamic referencing: object type defined at runtime

267
Q

What are some properties about destructors in objective C

A

-Must always be called dealloc
-always called automatically by the runtime
-never explicitly called

267
Q

What is introspection in objective C?

A

Introspection refers to the ability of an object to examine itself at runtime and reveal information about its properties, methods, and relationships.

268
Q

How can i implement destructors (dealloc) in objective C?

A

@interface Person : NSObject
@end

@implementation Person
- (void) dealloc
{
// do some clean -up operations
// then call the parent class’s destructor:
[super dealloc];
}
@end

269
Q

What is manual retain-release in objective C?

A

Is a technique where the programmer is explicitly responsible for allocating and deallocating memory for objects, it keeps track of how many owners an object has.
It’s implemented using a model called reference counting which is provided by NSObject and the Objective C runtime

270
Q

How does reference counting work in Objective C

A

you create a new object
-reference count is set to 1

you claim ownership of an object
-reference count is incremented by 1

you relinquish ownership of an object
-reference count is decremented by 1

object exists while reference count is greater than zero
object is destroyed when the reference count becomes zero

271
Q

What do these reference counting methods do and how do they effect the reference count of an object?
alloc
retain
copy
release
autorelease

A

Create an object and claim ownership of it and set reference count to 1

Claim ownership of an existing object and increase reference count by one

copy an object and claim ownership of it,and set reference count to 1

Relinquish ownership of an object and decrement its reference count by 1

Relinquish ownership of an object but defer it’s destruction

272
Q

What is Automatic Reference Counting(ARC)

A

needs to be switched on in Xcode
works the same way as manual reference counting, except …
… it automatically inserts appropriate retain and release calls
means you must not explicitly call retain, release or autorelease
means you usually do not need a custom dealloc method

273
Q

What do sockets do?

A

Enable two nodes on a network to talk to each other

274
Q

What are the 5 server side socket steps

A
  1. create a socket
    (socket)
    2.set socket options
    (setsockopt)
    3.bind the listener process to a specific port number
    (bind)
    4.start listening
    (listen)
    5.whenever a client requests a connection
    -accept a connection request from a client
    (accept)
    -exchange data with the client
    (send, read)
    -close connection
    (close)
275
Q

What are the three client side socket steps

A

create a socket
socket
request a connection
connect
exchange data with the server
send, read

276
Q

Threads are lightweight processes, what advantage does this bring?

A

faster to create

faster to switch between

faster to communicate between
-but only using global or static variables

277
Q

What is mutex and how does it work?

A

Its a locking mechanism for threads known as mutual exclusion, this means only a single thread can access a shared resource at any time

Threads can lock resources while they are using them and unlock resources when they are done

278
Q

What is semaphore and how does it work

A

Synchronization tool used to control access to shared resources. It acts like a flag that regulates how many threads can access the resource at a time.

The semaphore has a count which dictates how many threads can access the resource, when the counter is at 0 then no new threads can access it

When a thread access the resource is decrements the count and it increments it when it’s finshed

279
Q
A