Exam Flashcards
Is C strongly typed? Why?
No, C is weakly typed
You can convert between data types (eg casting pointers)
What is gcc?
GNU Compiler Collection is a compiler for C and C++
Is C statically or dynamically typed?
Statically - you must declare the datatype of a variable
How much memory does it require to store a character?
Unknown - variable memory space is machine specific
How do you store a boolean?
There is no boolean datatype in C
You have the equivalent by using 0 to represent False and any other number to represent True
What is the missing line, for ANSI standard C?
int main(){ for ( i=0; i<10; i++ ){ /* some code */ } }
int i;
In ANSI standard, the iterative variable must be declared before use in the for loop
True or False, it is guaranteed that arrays are stored in contiguous memory?
True
Strings are just _____________
an array of characters
Which string function returns the length of the string?
strlen(string)
Which string function copies a string ‘string1’ into ‘string2’?
strcpy(string2, string1)
Which string function concatenates string2 onto the end of string1?
strcat(string1, string2)
What string function would you use to determine if string1 and string2 were equal?
strcmp(string1, string2)
Note that this returns 0 (which means false) if the strings are equal
How can you use string functions in your C program?
#include <string.h>
What are four uses for random numbers?
Simulations
Machine Learning
Cryptography/Codes
Games
What are some characteristics of rand()?
The number returned is an integer
The number is very large
The number is the same each time the program is run
What does this code do?
int i; for (i=1; i<=10; i++){ printf("number %02d: %f\n",i,10.0*float)rand()/RAND_MAX); }
Prints 10 random numbers, between 0 and 10
How would you ensure that rand() gives different numbers every time a program is run?
You should seed the random number generator using:
srand(/*current time*/)
What is the best method for generating random numbers?
Using the GNU Scientific Library (GSL)
What is the definition of a function?
A function is:
- a uniquely named group of program statements
- which accepts zero or more arguments
- and returns zero or more values to the calling code
What is a function prototype? Why use them?
Functions must be declared before being defined
The compiler (which is one-pass) needs to know a function definition’s format before it is used
What is Scope?
Variables that are declared within a function’s scope are only accessible within the function
In general, it is very bad practice to use global variables/scope
What is the name for a function which does not return any values?
Procedure
What is a static variable? How are they used? Give an example use for it
Static variables are initialised once, when the function is first called. They retain their value when they go out of scope.
They are declared using the static
keyword
An example use would be counting page numbers within a function called ‘turnPage’
What is the definition of a pointer?
A variable which stores the address of another variable
What does &x
mean?
The location in memory (its “address”) where x is currently stored
What does *x
mean?
go to the memory address stored in x and bring back the value stored there
What is a void pointer?
A void pointer can point to any datatype, but must be cast when used
What are two runtime errors? Why are they caused?
Memory Fault and Segmentation Fault
Trying to access memory which is not allowed access. Trying to access memory in a way which is not allowed
When using malloc()
, what must you do?
Ensure that malloc()
was successfulfree()
the memory when you no longer have need for it
What does malloc() do?
Dynamically allocates memory at runtime, returning a void pointer to the memory that was allocated
What does pass by value mean? What is the opposite? How could this be achieved?
Pass by Value - creates a copy of the value held into the function, the original value remains unchanged
The opposite is pass by reference. In C, In order to update the value of a variable within a different function, it must be passed as a pointer.
How would you pass arguments to the main function?
int main(int argc, char **argv){
argc - the number of arguments passed
argv - the array of string values
What is scanf()
? What is it used for?
Returns the number of data items successfully assigned a value
It is like the reverse of printf()
, almost like input()
from python
What is a Stream?
- An abstraction of a file
- Is buffered
- May be text or binary
How do you open a stream? What else must you always do?
file = fopen("fileName.txt", "fileMode");
You should always ensure that it was successful, and close the stream when are finished
In C, what are the three standard streams?
stdin - input from the keyboard
stdout - output to the terminal (normal messages)
stderr - output to the terminal (error/warning messages)
What is a compiler directive? Why use them?
An instruction to the compiler for an action which occurs before compilation
Used for:
* Giving your programs access to useful library functions and values
* Controlling what code gets compiled
* Defining macros to make your code more readable
* Defining macros for values that might change in the future
How would you define and use a macro?
#define TEN 10
can be used int a = TEN * 5;
it is common practice for the macro to be in uppercase
What is a Macro?
- You can define a macro and replace any instances of the macro name with its definition
- It is standard practice for them to be written in uppercase
- The compiler replaces instances of macros with their definitions before compilation
What does typedef
do? Why use it?
Creates an alias for existing datatypes
It allows for better code readability
What are the four Storage Classes?
- Auto/Default - (should be) declared at the start of a block, storage allocated when block is entered and freed when block is finished
-
register
- variable is stored in CPU registers, cannot be pointed to since it has no memory address -
static
- Variable continues to exist even after the block (which it is in scope for) ends, its value is retained between repeated calls to the same function -
extern
- scope is global (usually bad practice)
What should be in a .h file?
What should be in a .c file?
.h - #include
s any required header files, defines macros and typedefs, declares function prototypes
.c - #include
s the .h file, fully defines each function in the .h file, (probably) contains a main function
What is a Structure?
A type of variable that groups multiple related data items together (the closest thing C has to a class)
What is a Linked List? Why use them?
A data structure containing an ordered sequence of nodes which link to one another
Can be used if you don’t know how many elements an array needs to hold; They are much more memory-efficient than inserting elements into arrays (and don’t have to be contiguous)
What are the three layers of UNIX?
Kernel - purely for interacting with the hardware
Shell - user logs in to interact with the kernel
Programs - interact with the shell
Every process has:
- A unique PID (process identifier)
- exactly one parent process
- zero or more children processes
What is Foreground and Background
Refering to processes
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
What does fork()
do?
Creates a child process as a duplicate of the parent, returning the PID of the child
The parent and child share everything from before the fork()
command, including variable values, stdout, etc
What is a pipe?
a unidirectional (one-way) flow of data between two processes
What are the three methods of communicating between processes?
- Signals - need to know the PIDs, no data can be transferred, the receiving process doesn’t have to keep checking
- Files - one processes writes into a file while the other reads from it, data can be transferred, the receiving process has to keep checking
- Pipes - the processes must be parent-child/siblings, data can be transferred, receiving process has to keep checking
What is the Virtual Address Space?
- Each process runs in its own lump of memory
- The virtual memory space starts from address 0
- The memory space is usually contiguous
- The OS maps the virtual address to actual, physical addresses (using page tables)
What are the benefits of using Virtual Address Space?
- Transparency - processes are unaware of virtualisation
- Protection/Isolation - processes cannot interfere with one another
- Flexible Memory Management - the OS can move things around as required
- Shared Memory
- Dynamic Memory Allocation - a process can request for its memory to be increased
- Paging - gives the illusion of unlimited memory
What is MMU?
Virtual Memory Space
Memory Management Unit (in the CPU)
What is TLB?
Virtual Memory Space
Translation Lookaside Buffer - a cache of recently used address mappings
What does setjmp()
do?
Saves the contents of the registers to a buffer
What does longjmp()
do?
Restores the contents of the registers from a buffer
What is the difference between Subroutines and Coroutines?
Subroutines - run to completion and then return to the same place they were called from
Coroutines - can switch between functions at multiple different points (they are concurrent, but not parallel)
C++ is nearly a superset of C, what features does it add?
- Classes
- Function + Operator Overloading
- Exception Handling
- Default Parameter Values
- Pass By Reference
What is a precompiler?
A precompiler modifies the source code for the compiler
What is function overloading? How is it used?
When two or more functions use the same name
Each function must have either:
* a different number of parameters
* different parameter types
In C++, what do new
and delete
do?
new
- malloc()
s memory for the object, then calls the constructordelete
- calls the destructor for the object, then free()
s the memory
What does this
mean, in C++? When should it be used? What is the Objective-C equivalent?
this
points to the current object - to avoid ambiguities, to allow objects to be passed to/from functionsself
is the Objective-C equivalent
What are Static Member Variables?
Variables which are shared by all instance members of a class
They can be accessed even if no objects of the class exist
Does C++ allow inheritance?
Yes, classes in C++ can inherit from base classes. In fact, C++ allows Multiple Inheritance, from any number of base classes
When are the base and derived class constructors/destructors called?
Constructors are executed in order of derivation
Destructors are executed in reverse order of derivation
How can parameters be passed to base class constructor functions?
The constructor of the derived class can call the constructors of the base classes
What is a friend function? Is friendship inherited?
C++
A non-member function (defined outside of the class) which can access private and protected elements of the class (such as variables)
Friendship is not inherited nor transitive
What is Operator Overloading? What is its intended purpose?
Creating more than one ‘meaning’ of an operator
They are to make life easier for users of a class, not to make shortcuts for developers
What is a Function Template? How do you create one?
Instructions for how to build a family of similar looking functions (usually for parameters to be each datatype)
template<dataname T> void sum (T a, T b){ T sumAB = a + b; }
What is a Class Template? How do you create one?
Instructions for how to build a family of similar looking classes (usually for parameters to be each datatype)
template<typename T> class Stack { T stck[SIZE]; int index; public: static int count; Stack(); Stack(Stack &); ~Stack(); void push(T); T pop(void); }
Some data structures, such as stacks/queues, are so widely used that C++ provides a set of standard templates through the _____?
Standard Template Library
C++ allows for exceptions, how can this be done?
By doing:
~~~
try{
throw 20; // raises exception with integer 20
}
/* for specific exception type /
catch (int e){
printf(“Exception: %d\n”, e);
}
/ for any exception */
catch (…){
printf(“Exception”);
}
~~~
What does typeid(x)
do, and how could you use it?
Returns the type of object x
Could be used for:
~~~
if ( typeid(x) == typeid(MyClass) ) {
cout «_space;“x is MyClass” «_space;endl;
}
~~~
What are the C++ equivalents of the standard streams in C?
std::cin - equivalent to stdin
std::cout - equivalent to stdout
std::cerr - equivalent to stderr
(Including using namespace std;
at the beginning of your program removes the need for the std::
in the streams)
Explain Little-Endian vs Big-Endian. Which is Linux?
Little Endian - Least significant (smallest) digit is first, eg 321 represents 3 + 20 + 100 (=123)
Big Endian - Most significant (largest) digit is first, eg 123 represents 100 + 20 + 3 (=123)
Linux is Little-Endian
What is the benefit of Little-Endian?
Using a little-endian system is more efficient for type conversions, since the pointer (to the starting memory address) does not have to change when the size of the variable changes
What does const int x
mean?
That the value of x
cannot change after initialisation, any attempt to do so results in a compile-time error
What is a Variadic Function? What is/isn’t acceptable?
Functions which can accept a variable number of arguments
They must have at least one name parameter (which must come before …):int badFunction (...)
is not allowedint goodFunction (int a, ...)
is allowed
Is C++ a Strict Superset of C? Is Objective-C?
C++ is not a superset of C (but it is nearly)
Objective-C is a strict superset of C
What are two object-oriented frameworks for Objective-C?
Foundation - classes for basic data structures and for interacting with the OS
AppKit - classes for developing applications, windows, buttons, etc.
Why use #import
instead of #include
?
In Objective-C
#import
includes an implicit #import guard
Is this C, C++, or Objective-C?
MyObject *obj = [MyObject new]; [obj callWith:parameter1 and:parameter2];
Objective-C
Is this C, C++, or Objective-C?
myFunction(parameter1,parameter2);
C
Is this C, C++, or Objective-C?
MyObject *obj = new MyObject; obj->myMethod(parameter1,parameter2);
C++
What is a Wrapper Class? Provide an example
Objective-C
a class which wraps one or more primitive data types, eg NSNumber, NSString, etc.
Is “All objects are pointers” a true statement for C++ or for Objective-C?
It is true for Objective-C
Memory for objects is always allocated in the heap: NSNumber *num
not in the stack: NSNumber num
(this gives a compile-time error)
What is this called?
BOOL b = YES; NSNumber *num1 = @43; NSNumber *num2 = @'A'; NSNumber *num3 = @91.6; NSNumber *num4 = @b; NSLog(@"%@, %@, %@, %@,\n", num1, num2, num3, num4); // 43, 65, 91.6, 1
Literal Syntax
What do the +
and -
mean? Is age
public or private?
@interface Person: NSObject { int age; } - (void)setAge:(int)age; \+ (void)sayHello; @end
+
- Class Methods-
- Class Instance Methods
age
is private (since this is the default for Objective-C)
What are the constructors and destructors for Objective-C?
Constructor:
* method name always starts with init
* called after alloc
Destructor:
* always called dealloc
* always called automatically by the runtime; never explicitly called
What does (id)
mean, in Objective-C?
(id)
is a datatype which points to any type of object (similar to a void pointer, in C). It supports dynamic referencing (object type is defined at runtime)
What is MRR?
Manual Retain-Release
- you explicitly manage memory by keeping track of how many owners an object has
- implemented using reference counting model
What is Reference Counting?
- You create an object - reference count is set to 1
- You claim ownership of an object - reference count increases by 1
- You relinquish ownership of an object - reference count decreases by 1
An object exists while the reference count is greater than 0
Object is destroyed (at some point by the garbage collector) when the reference count becomes 0
What is ARC?
Automatic Reference Counting
does not run in gcc, needs to be switched on in Xcode. It 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
What is Memory Leakage?
When memory, which has been allocated (via malloc()
), is no longer accessible - usually caused by a variable going out of scope before being freed