C Flashcards

1
Q

Which of these does C have?
- Explicit memory management
- Runtime error checking
- Exception handling
- ANSI/ISO standards

A

Has:
- Explicit memory management
- ANSI/ISO standards

Does not have:
- Runtime error checking
- Exception handling

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

What are the 6 things that define C?

A
  • Imperative (describes computation in terms of statements that change a program state)
  • Procedural/functional
  • Compiled
  • Statically (types are checked before runtime), weakly (supports implicit type conversions) typed
  • Available on just about every platform (portable)
  • Very fast
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How are C programs compiled and linked?

A

They are compiled into objects (.o) and then linked into an executable (.exe)

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

What are the base datatypes and their associated memory allocation, range and precision?

A
  • Unsigned char (1 byte, 0 to 255)
  • Char (1 byte, -128 to 127)
  • Unsigned short int (2 bytes, 0 to 65, 535)
  • Short int (2 bytes, -32,768 to 32, 767)
  • Int (4 bytes, -2,147,483,648 to 2,147,483,647)
  • Long int (8 bytes, +/- 9 x 10^18)
  • Float (4 bytes, +/- 3.4 x 10^-38, +/- 3.4 x 10^38, 6 digits)
  • Double (8 bytes, +/- 1.07 x 10^-308, +/- 1.07 x 10^308, 15 digits)
  • Long double (16 bytes, +/- 3.4 x 10^-4932, +/- 3.4 x 10^4932, 18 digits)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you show variables in printf statements?

A

Char - %c
Int - %d
Float/double - %f
Long double - %Lf

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

Why does “char ch = ‘A’” print 65 if trying to display ch as %d?

A

It follows the ASCII table, and the follows for all other characters

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

What issue arises with if statements in C?

A

There is no explicit boolean datatype in ANSI C. A condition is evaluated to an int value: 0 = false, anything else is true.

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

What is the difference between “a = 0” and “a == 0” in an if statement?

A

“a = 0” means that the if statement equates to 0, or “if(false)” and therefore cannot be true. “a == 0” means that does a hold the value that is 0. If it does then the statement is true.

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

What do | and & represent?

A

Bitwise OR and Bitwise AND respectively

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

What do || and && represent?

A

OR and AND respectively

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

What do BREAK and CONTINUE mean in a loop?

A

BREAK: Jump to the next command after the end of the loop
CONTINUE: Jump to the start of the next increment

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

How does C store a string?

A

A string is an array of characters

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

How are strings and characters represented?

A

Characters use single quotes and strings use double quotes.

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

How are strings terminated in memory?

A

Using the null character. All strings in C are “null terminated”

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

What does an array contain if it is uninitialised?

A

It will contain random stuff

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

What does weakly typed mean?

A

Supports implicit type conversions

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

What three things must a function have in C?

A
  • Have a uniquely named group of program statements (so no overloading)
  • Accept zero or more arguments or parameters
  • Return zero or one value to the calling code
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How is a function called that returns an integer?

A

int doubleIt(int a Number) { … }

int b = doubleInt(3)

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

Why do functions need to be declared like variables?

A
  • The (one-pass) compiler needs to know a function’s definition before it is called
  • Functions may appear in any order in the program module (main function is first by strong convention)
  • 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
20
Q

Are global variables used in C?

A

It is bad practice to use global variables. Variables only exist when they are in scope.

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

What does the keyword “static” do?

A

It initialises the variable when the function is first called and retain their value when they go out of scope

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

What is a shell in Linux and Unix?

A

A command-line interpreter for the OS and the outer layer of the OS surrounding the kernel

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

How does the section of code work line by line?

char ch = ‘A’;
char *p;
p = &ch;

A
  • Variable ‘ch’ is a character
  • Variable ‘p’ is a pointer to a character
  • ‘p’ is assigned to be the pointer to ch
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

If x is any datatype, then what is &x?

A

&x is the location in memory (its ‘address’) where x is currently stored

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

If x is a pointer, then what is <datatype> *x</datatype>

A

<datatype> *x declares x to contain the memory address of a variable of type <datatype>.
*x says: go to the memory address stored in x and bring back the value (of type <datatype>) stored there
</datatype></datatype></datatype>

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

How much memory is used to store a pointer in Windows 32-bit and Windows 64-bit respectively?

A

4 bytes and 8 bytes

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

What two runtime errors can occur from using pointers?

A
  • Memory fault
  • Segmentation fault
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What causes runtime errors using pointers?

A
  • Trying to access memory to which it is not allowed access
  • Trying to access memory in a way that is not allowed (e.g. trying to overwrite the OS)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What possible solutions may be used to solve the issue of at compile time not knowing how much memory is needed at runtime?

A
  • Declare an array whose size is decided at runtime (But there is no way of knowing how much free contiguous memory is available. And you might not know how much is required before declaring the array)
  • Process the data in smaller chunks (Possible, but this requires a lot of extra programming).
  • Dynamically allocate memory at runtime using pointers (Here we can check whether memory allocation was successful).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

How can memory be allocated to a variable at runtime?

A

(Example is for an int)

int *p = NULL;

p = (int *)malloc(23); //23 bytes
p = (int )malloc(23sizeof(int)); //23 integers

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

What should happen if there is not enough memory?

A

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
32
Q

What happens to a ‘normal’ variable when it goes out of scope?

A

Its allocated memory is released

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

What happens to dynamically allocated variables when they go out of scope?

A

A memory leak occurs. Allocated memory is not released, even though the variable goes out of scope.

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

What must be done to prevent a memory leak?

A

The memory must be explicitly freed before the variable goes out of scope.

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

What happens if you attempt to free memory that has been freed, or memory not allocated by malloc?

A

‘behaviour is undefined’

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

int main ()
{
char c = ‘A’;
printf(“Before: c = %c\n”,c);
myFunctionA(c);
printf(“ After: c = %c\n”,c);
}
void myFunctionA (char ch)
{ ch = ‘B’; }
Why is the value of c not changed?

A

It is not updated because ch is a copy of c.

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

int main ()
{
char c = ‘A’;
printf(“Before: c = %c\n”,c);
myFunctionA(c);
printf(“ After: c = %c\n”,c);
}
void myFunctionA (char ch)
{ ch = ‘B’; }
How do you update the value of c?

A

In order to update the value of a parameter within a function it must be passed as a pointer. The value of the thing passed cannot be changed. The memory address where c is stored should be copied, (and is not updated), not c’s value.

int main ()
{
char c = ‘A’;
printf(“Before: c = %c\n”,c);
myFunctionA(&c);
printf(“ After: c = %c\n”,c);
}
void myFunctionA (char *ch)
{ *ch = ‘B’; }

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

int main ()
{
char *p = NULL;
myFunctionB(p);
printf(“p = %s\n”,p);
}
void myFunctionB (char *str)
{
strcpy(str,”Hello”);
}
Why does this code produce a ‘Memory fault (coredump)’?

A

p is uninitialised, so contains random stuff. The random stuff is then copied from p into str when the function is called. When strcpy is called, the text is stored in whatever random address is in p and hence str. The result is likely to be a memory fault, depending on what that random address is.

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

int main ()
{
char *p = NULL;
myFunctionB(p);
printf(“p = %p: %s\n”,p,p);
}

void myFunctionB (char *str)
{
if ( !(str = (char *)malloc(6)) )
{
printf(“Insufficient memory\n”);
exit(-1);
}
strcpy(str,”Hello”);
printf(“str = %p: %s\n”,str,str);
}
Why does malloc change the value of str, but value of p remains unchanged?

A

The random stuff is copied from p into str when the function is called. malloc reserves 6 bytes of memory and the memory address of the first byte is stored in str. So str is correctly updated but p is not changed.

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

Can you have a pointer to a pointer and why?

A

Yes, as a pointer is just another datatype

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

int main ()
{
char *p = NULL;
setString(&p);
printf(“p = %p: %s\n”,p,p);
}

void setString (char str)
{
if ( !(
str = (char )malloc(6)) )
{
printf(“Insufficient memory\n”);
exit(-1);
}
strcpy(
str,”Hello”);
printf(“
str = %p: %s\n”,str,str);
}
Why does this code work correctly?

A

The memory address of p is stored at str, making *str the same as p. malloc reserves 6 bytes of memory, and the memory address of the first byte is stored in *str. Therefore, *p is the memory address where the text is held.

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

How do you pass arguments to the main function?

A

This will be done in the command line. In order to define main,
‘int main( int argc, char **argv )’
must be written. argc is the number of arguments passed, and **argv is the array of string values. These names are standard.

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

What is ‘parameter 0’ when passing arguments into main?

A

It is always the name of the executable.

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

int Plus (int a, int b) { return a+b; }
int Minus (int a, int b) { return a-b; }
int Multiply (int a, int b) { return ab; }
int Divide (int a, int b) { return a/b; }
int doFunction (int a, int b, int (
myFunc)(int,int) )
{ return myFunc(a, b); }
What do these set of functions do?

A

The third parameter of ‘doFunction’ is a pointer to a function that take two int values as parameters and returns an int value. This can be any of the first 4 functions.

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

In Linux, how do you view a list of files in your home directory?

A

‘ls -al ~/’ (home directory is ~/)

46
Q

Where is command history stored by default?

A

.bash_history

47
Q

How do you view the 10 most recent commands you have entered?

A

history 10

48
Q

How can you re-execute the most recent command starting with ‘cd’?

A

!cd

49
Q

What do ‘grep’ and ‘find’ do in Linux command line?

A

grep: find text in files using regular expressions
find: find files in a directory structure based on different characteristics

50
Q

What is scanf()?

A

It is like the reverse of printf(). It uses &variable as its destination as this is the memory address of the variable.

51
Q

What is a stream in C?

A
  • Is an abstraction of a file (provides a consistent interface to the programmer, regardless of the actual device)
  • Is buffered (data is not necessarily written to the device when the write command is issued. You can force the write to happen by flushing the stream)
  • May be text or binary (text stream = sequence of character + character translation such as newline; binary stream = sequence of bytes + no character translation)
  • Need to include #include stdio.h
52
Q

How is a file opened in C?

A

FILE *filepointer;
filepointer = fopen(“textfile.txt”, “r”);
if (filepointer == NULL) {
//error handle
};
MUST ALWAYS TEST THAT OPENING THE FILE WAS SUCCESSFUL

53
Q

What is ‘int errno’?

A

The value is updated when an error occurs. This value can be reset to 0. To access this error, strerror(errno) will return the error message in a printf statement.

54
Q

What does a call to ferror(fp) do?

A

It determines whether the most recent operation on the file pointed to by fp produced an error. It returns a 1 if an error occurred; 0 if not. The value is reset by each file operation.

55
Q

What are the 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)
56
Q

Where must error messages be sent?

A

Error messages must be sent to stderr and not stdout.

57
Q

What is a compiler directive?

A

A compiler directive are actions that are taken by the compiler before compilation

58
Q

What does the compiler directive ‘#include <stdio.h>' do?</stdio.h>

A

Find the file called stdio.h and copy its contents into the current position in the program, replacing this line

59
Q

What is the difference between ‘#include <>’ and ‘#include “”’?

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>

60
Q

What does ‘#define’ do?

A

Defines a macro and replace any instances of the macro name with its definition.

Example:
#define ELEPHANT “Size of an elephant!”

61
Q

What cautions need to be taken into consideration when using ‘#define’?

A
  • Definitions are substiuted before the compiler compiles the source code, so an error introduced is hard to trace.
  • The direct substitution can lead to unexpected results.
62
Q

What do these selective compliation statements do?
- #ifdef
- #ifndef
- #undef
- #else
- #elif
- #endif

A
  • If a macro is defined
  • If a macro is not defined
  • Undefine a macro
  • Otherwise
  • Else if
  • End of the #ifdef or #ifndef block
63
Q

What do these predefined macros do?
- __FILE__
- __LINE__
- __DATE__
- __TIME__
- __STDC__

A
  • The current file name
  • The current line number in this file
  • The date this object code was generated from the source
  • The time this object code was generated from the source
  • 1 if this implementation of C conforms to the ANSI/ISO standard; an other value means it does not
64
Q

What are the macro name conventions?

A
  • Macro name is all capitals (to make code easier to follow)
  • System macros start with two underscores (so that they do not interfere with own macros)
65
Q

What should be done when a header file is created?

A

The header file is ALWAYS named after the code file it belongs to

66
Q

What are structures in C?

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

How are structures declared?

A

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

68
Q

What does ‘typedef’ do?

A

This creates your own datatypes

typedef struct structName EXAMPLE

69
Q

What is a linked list?

A
  • A data structure
  • An ordered sequence of nodes (each nodes consists of data, and one or more links to other nodes to record the sequence)
  • A memory-efficient means of storing large data structures (or where the final size of the large data structure is unknown at compile time)
  • A speed-efficient means of inserting and deleting nodes
70
Q

How is an element inserted into an ordered array?

A
  • If there is enough space in the array, all elements are shuffled along before the new element is inserted
  • If the array is already full, then it has to be expanded first
71
Q

How are arrays always stored?

A

They are stored in contiguous memory

72
Q

What are the advantages of arrays?

A
  • Can go directly to the nth element
73
Q

What are the disadvantages of arrays?

A
  • Insert/delete requires other elements to be moved
  • If a new element is to be inserted into a full array: either you have to stop, or you will have to extend the array which will often result in the whole array to be moved
74
Q

How do you set up a dynamic linked list in C?

A

struct anode {
// some data variables here
char data;
struct anode *nextNode; // circular definition
};
typedef struct anode NODE;

NODE *root = NULL;

75
Q

How do you add the first node to a dynamic linked list?

A

// allocate memory
NODE *newNode;
if ((newNode = (NODE *)malloc(sizeof(NODE))) == NULL) {…}

// set the new node’s values
newNode->data = ‘A’;
newNode->nextNode = NULL; // there is no next node at the moment

// add it to the empty list
root = newNode;

76
Q

How do you add a second node to a dynamic linked list?

A

// at the beginning of the list
newNode->nextNode = root;
root = newNode;

// at the end of the list
root->nextNode = newNode

77
Q

How do you insert a node into a dynamic linked list?

A

Find the right place to insert the new node. Link the new node to the tail of the list. Link the head of the list to the new node. Link the head first means that all the other data is lost.

78
Q

What are the advantages to a dynamic linked list?

A
  • It does not matter where in memory each node is stored
  • Insert/delete requires only changing the values of 1 or 2 pointers
  • Size of linked list is limited only be computer memory
  • One list may be linked in more than one way
79
Q

What are the disadvantages of linked lists?

A
  • To find an element, must start from the beginning and follow the pointers. This can be sped up by using additional pointers
80
Q

What are the four cases for adding a new node to a linked list?

A
  • Add the first node to a new list
  • Append a node to the end of the list
  • Insert a node at the beginning of the list
  • Insert a node into the middle of the list
81
Q

What are the four cases for deleting a node from the list?

A
  • Delete a node from the middle of the list
  • Delete the node at the beginning of the list
  • Delete the node at the end of the list
  • Delete the last node in the list
    (Each node must be freed once it has been deleted as the have been malloc-ed)
82
Q

What are some common types of linked data structures?

A
  • Stacks
  • Queues
  • Circular lists
  • Trees
83
Q

What are the three layers UNIX?

A
  • Programs
  • Shell
  • Kernel
84
Q

What is telnet and how does it differ from ssh?

A
  • Virtual terminal connection
  • Application layer protocol over internet or local area network
  • Interactive text-oriented communication

telnet is unencrypted whereas ssh is an encrypted version of telnet.

85
Q

What happens in a multi-tasking OS such as Linux?

A
  • Each process runs in its own lump of memory its virtual address space
  • Each virtual address space starts at memory address zero
  • The OS maps virtual memory addresses to real, physical memory addresses using page tables
  • The virtual address space is usually contiguous (in some other OSs it may be segmented)
86
Q

What are the benefits of virtual memory addressing?

A
  • Transparency (processes are unaware of virtualisation)
  • Protection and isolation (one process cannot interfere with another)
  • Flexible memory placement (OS can move things around in memory )
  • Shared memory and memory mapped files (efficient interprocess communication and shared code segments, i.e. dynamic libraries)
  • Dynamic memory allocation (grow memory usage on demand)
  • Paging (Creates the illusion of near-infinite memory)
87
Q

What is stored in virtual address space?

A
  • Kernel (shared)
  • Stack (which goes top to bottom and includes auto variables)
  • Libraries
  • Heap (from bottom to top and is dynamically allocated (via malloc)
  • BSS (Block started by symbol and includes uninitialised static variables)
  • Data (includes initialised static variables)
  • Text (program machine code and constants)
    The rest is unused. The bottom three things are all from the excutable.
88
Q

What is a potential problem with heap allocation?

A

It can cause fragmentation

89
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:
- sp (stack pointer)
- bp (base pointer)
- pc (program counter) (the statement currently being executed)

90
Q

What does setjmp do?

A

Saves the contents of the registers to a buffer

91
Q

What does longjmp

A

Restores the contents of the registers from a buffer

92
Q

What is the difference between subroutines and coroutines?

A

Subroutines can suspend functions once using ‘return’, whereas coroutines can suspend functions frequently using ‘yield’ at certain ‘suspension’ points.

93
Q

What is 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 CPUs

94
Q

How do coroutines used in computer games maintain a higher framerate?

A
  • You have a computationally heavy routine that needs to run
  • You do not want that entire routine to run within one frame as 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
  • Coroutines allow the computationally heavy routine to be spliy across multiple frames rather than requiring it to finish in one
95
Q

How do coroutines work in the stack?

A

The stack frames of the two routines stay on the stack, with the base and stack pointers changing based on which coroutine is being used

96
Q

What happens if you run rand() a few times?

A
  • The number is an integer
  • The value is very big
  • You get the same number each time you run the program
97
Q

What is big endian and little endian?

A

Big endian: biggest digit first (123 = 100 + 20 + 3)
Little endian: littlest digit first (321 = 3 + 20 + 100)

98
Q

What endian system does C use?

A

Little endian

99
Q

What are bit fields?

A

Bit fields allow you to address smaller units of memory than one byte. It does not have to be just one bit

100
Q

What is the different between a structure and a union in terms of variable storage?

A

In a structure, each variable is stored in different memory. In a union, each variable is stored in the same memory

101
Q

Even though little endian is counter-intuitive, why is it useful?

A

C is weakly typed, therefore there is implicit type conversion.

char c = 43; always 1 byte
long int i = c; in our system: 8 bytes
short int s = i; in our system: 2 bytes

102
Q

What are the bitwise operations?

A
  • AND &
  • OR |
  • XOR ^
  • one’s compliment ~
  • Binary left «
  • Binary right&raquo_space;
103
Q

What is the const modifier?

A
  • Constant variable (variable’s value cannot be changed after initialisation)
  • Pointer to a constant variable (the thing being pointed to cannot be changed)
  • Constant pointer to a variable (cannot change the pointer, but can change the value it is pointing to)
  • Constant pointer to constant variable (neither pointer nor thing being pointed to can change)
104
Q

What are enumerations?

A

A set of user-defined integral constants.By default, values start at 0 and increment. These values can be changed

105
Q

What is a variadic function?

A

A function that can accept a variable number of parameters. They must have at least one named parameter and the named parameters must come first. Three dots are used to represent the other parameters

106
Q

What is a socket?

A

Enables two nodes on a network to talk to each other

107
Q

What are the steps for a server side creating a socket?

A
  • Create a socket
    (socket)
  • Set socket options
    (setsockopt)
  • Bind the listener process to a specific port number
    (bind)
  • Start listening
    (listen)
  • Whenever a client requests a connection
    accept a connection request from a client
    (accept)
    exchange data with the client
    (send, read)
    close connection
    (close)
108
Q

What are the steps for a client side creating a socket?

A
  • Create a socket
    (socket)
  • Request a connection
    (connect)
  • Exchange data with the server
    (send, read)
109
Q

What are the return values of fork() in C?

A
  • fork() < 0: The creation of a child process was unsuccessful
  • fork() = 0: Returned to the newly created child process
  • fork() > 0: Returned to the parent or caller. The value contains the process ID of the newly created child process
110
Q

What is an exec function?

A

It allows a process to replace itself. They are all wrappers of the execve function. Error handling will need to be done for if the exec call fails.