0% found this document useful (0 votes)
8 views19 pages

CP264 Midterm Prep

Uploaded by

takuminft
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views19 pages

CP264 Midterm Prep

Uploaded by

takuminft
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

CP264 Midterm Prep

C Compiling, Execution, & Memory Map


Compiling Process
1. Preprocessing
o Resolves lines with preprocessor drives (e.g. Lines start with "#")
2. Compilation
o Convert C source code program into assembly program
o Assembly Program: Sequence of readable machine instructions such as read/write data
from/to memory to/from CPU registers
3. Assemble
o Convert assembly program to object program
o Object Program: Binary machine program (i.e. Machine code)
4. Linking
o Combine necessary object programs together to create executable program of binary
machine program
Execution Process
1. Console starts new process that loads executable program into main memory
2. Starts execution of program from first instruction of the main function
o One by one controlled by program's flow control
 At execution, instruction is read from memory to CPU
 CPU performs operation according to instruction
 After instruction execution is done, program flow control goes to next
instruction
3. Execution stops at the end of the main function
4. Process of running the program exits; console returns prompt for next command input
Memory Management of Program Executions
Two major parts:
1. Program Memory
o Text Region: Stores functions
2. Data Memory
o Data Region: Stores static and global variables
o Stack Region: Stores parameters and local variables of function when function is called
o Heap Region: Holds runtime dynamic data
 When program is called to run by OS:
1. Loads all functions to text region; static and global variables to data region
2. Execution starts from calling main function
3. When function is called, argument and local variables of function are stored in stack
region by program
Basic Syntax, Keywords, Program Structure, Flow Controls
Basic Syntax

Keywords

Program Structure
 Imperative Programming: Statements executed strictly one after the other
 Procedural Programming: Organizing statements into functions
 C source program organized as sequence of functions
o Must contain main() function for executable function; execution of C program begins at
main() function
o Function contains logical sequence of statements
o Order matters when writing functions!
 Can't call function A from function B if function A is declared after function B
 After compiling, an executable program is organized in a sequence of blocks of functions
 Program Structure Model:
Flow Control
 Flow Control: Controls of orders of statements/instructions of executable programs
 3 Basic Flow Control Structures:
1. Sequence Control: Executes program instructions in linear order of their appearances in
program (default)
2. Selection Control (aka Decision or Branching): Enables jump from one instruction to
another depending on condition
4 Decision Control Statements:
a. if statement
 Note: Block scope braces {} can be eliminated if there's only one
statement block
 Note: Can be compressed further to become

b. if-else statement
 Ternary Operator: If condition is true, use expression1, else use
expression2
 Syntax: condition? expression1 : expression
c. if-else-if statement
d. switch statement
3. Repetition Control (aka Loop): Executes block of statements over and over until certain
condition is satisfied
3 repetition statements:
a. for loop
b. while loop
 executes condition first; if true, executes loop block
c. do-while loop
 executes loop block first, then checks conditions
Data Types, Variables, Constants
Data Types
 Data Type: Defines how certain type of values are represented and operated in programming
Used to inform compiler about:
o Type of data stored
o How much space in memory data recquires
o Operations that can be applied to data
 8 Primitive Data Types:
o char
 Uses 1 byte
 Represents integers from -127 to 127
 Uses ASCII to map integers from 0 to 127
 RECALL: ‘A’ = 65; ‘a’ = ‘A’ + 32 = 97
o int
 Uses 4 bytes
 Represents integers from -231+1 to 2-31-1
 First bit from the left is a sign bit (0 for positive, 1 for negative)
 2 ways to store 4 byte int type in memory block of size 4:
 Little-endian: Stores least significant byte in smallest address memory cell
 Big-endian: Stores most significant byte in smallest address memory cell
o float
 float types → 4 bytes for single precision floating point numbers
o double
 double types → 8 bytes for double precision floating point numbers
o short
o long
o signed
o unsigned
 Arithmetic operations applied to primary types
 Keywords short, long, signed, and unsigned are modifiers for int type
o ∴ can't use them for arithmetic operations!! Can only use the primary types in purple
 Data Type Size: Number of bytes needed to store data value of the type in memory
 Value Range: Range of values data type can hold

Variables
 Variable: Identifier of a data value in program; gets memory allocation at compile time and
instantiated at runtime
 When compiler encounters statement of variable declaration and assignment of value to it:
o Variable is allocated a memory block with relative address at compile time that's
mapped to a memory location of a computer system at runtime
 Size of memory block of variable is the size of the data type of the variable
o Variable is assigned a value in a source program
o Compiler generates instructions that write value to memory location of the variable at
runtime
 Local Variable: Variable declared within code block enclosed by {}
o Can be used in block after its declaration
 Global Variable: Variable declared outside a function
o Can be used in any function
o Relative memory location of variable is relative with beginning of scope

Constants
 Constants: Fixed data values in programs
 2 ways to define constants/read-only variables:
1. Preprocessor using #define
2. const keyword
Operations, Operators, Expressions, Operations
Operations & Operators
 Arithmetic Operations: Operation of two operands by operator (e.g. a+b)
 Constants operations and evaluations done by compiler
o Starts at right side; actual computing at compile time
 Variable operations computed at runtime
o Compiler generates instructions to do operation at runtime

 Note: In c there is no power (**) operation, you need to use pow()

Expressions
 Arithmetic Expressions: Consist of constants, variables, arithmetic operators, and parentheses
 Compiler parses right side expression, evaluates, and converts it to sequence of instructions of
operations
 Resulting Type of Arithmetic Operations:
o Two operands of same data type = result is in operands' data type
o Two operands of different data type = lower type operand converted to higher type
first, then do equation
 Order: char, int, long, float, double
 Overflow: Out of range data type after operation
 (Floating Point) Underflow: Operation produces result smaller than smallest floating number of
float type
 Correctness of Operation Computing -> Precision loss for each float/double type operation
Logic Operations
 Relation Operation: Compares two operands by relational operator, return 1 if true, 0 otherwise
o

 Boolean Expression: Consists of constants, variables, arithmetic expressions, relational


operators, parenthesis, and constructed by relational operators. Returns 1 if true, 0 otherwise
 Logical Operation: Operations on Boolean expression operands with logical operators
o Note: Single value or an arithmetic expression will be treated as a Boolean expression
(i.e. a && b is equivalent to a != 0 && b != 0)

 Logic Expression: Expressions consisting of Boolean expressions, logic operators, parenthesis,


and constructed by logic operations. Gives 1 if true and 0 otherwise
o Used to represent conditions in selection and repetition statements

Bitwise Operations
 Bitwise Operation: Operates on bit patterns (or binary numbers) at individual bit level
o Data types are unsigned data types including unsigned char, unsigned int, unsigned long
o Every bit of the types are involved in the operation
o Result of bitwise operation is the same type of its operands
 Bitwise Expression: Consists of constants, variables, bitwise operators, and parenthesis;
constructed by bitwise operations

Unary Operators

Functions, Variable Scope with Functions


Functions
 Function: Routine that can be called; useful because:
 Reuse of code
 Enable modularized design for effective development, understanding, and maintenance
 Organize large program
 Enable library contraction
 Needs to be declared/defined before it can be called
 Call stack of function calls:
1. When function is called argument and local variables of function are pushed to call stack
a. Instances of local variables and argument variables of function are allocated in
the stack region
b. Memory spaces reserved for variables in call stack
2. Argument and local variables are instantiated and have absolute addresses,
a. Parameter values copied to argument variable locations
3. After function call is done, argument and local variables of function will be popped off
from call stack so memory space in call stack can be reused by other function calls
4. If function f1 calls function f2, the argument and local variables of f2 are pushed to call
stack to top f1's argument and local variables; results in growing of call stack
 Due to this memory management mechanism, programs doesn't remember argument or local
variables of function after function call is completed
 Function call:
 Parameters passed must match parameter data types in declaration and/or definition
 2 methods to pass input into function:
 Pass-by-values
 Pass-by-values: Pass constant/variable value to function through
function parameters
 When making function call, copy of input data is stored in the stack so
operations on argument data don't impact variable outside function
 Changes to parameter variable do not impact argument variable passed
because a copy of the argument value was given to parameter
 Pass-by-references
 Pass-by-references: Pass addresses of input parameter variables to
function at runtime
o References: Terms in compile time
o Addresses: Terms at runtime
 Copy of address put in call stack so function can access and operate
input data through address
 Changes to parameter variable change argument variable passed
because they have the same address in memory
 *x = "the value at (address) x"
 &x = "address of x"
 Function dependency
 Calling of functions defines dependency relations of function
 Represented by directed graph with functions as nodes, directed edge from function f1
to function f2 if f1 calls f2, written as f1 -> f2
 Compiler converts functions to linearly ordered blocks of functions

Preprocessors
 Preprocessor Directives: Line starts with #
 Preprocessor resolves all preprocessor directives at preprocessing step of compiling
 Commonly used case:
o Include files (#include)
o Macro definitions (#define)
o Conditional compilation (e.g. #ifdef)

Libraries
 Library: Collection of predefined constants and functions, can be reused in creating new
programs
 Notable libraries:
o stdio: Input/Output → standard device and file input/output functions
o stdlib: General Utilities → functions that don’t fit to other headers
o math: Mathematics → common mathematical functions
o string: String Handling → functions for string operations
o time: Date & Time → functions for determining time and date
Pointers
 Pointer: Variable to hold memory address of another variable
Pointer is a tool to access data -
o Alternative method to access memory block and value stored at memory block
o Make it possible to do address operations to access data for data operations
o Address values of pointers are meaningful only at runtime
 & Operator: Gets address of a variable instance
 * Operator: Indicates a variable is a pointer; Gets/sets value stored at given address
 Pointer Applications:
o Used in pass-by-references; allows output of multiple values from function through
function arguments
o Increases efficiency of accessing data for algorithms
o Enable dynamic memory allocation and management
o Used to implement complex data structures (e.g. linked lists, queues, stacks, trees)
 Pointer Operations:
o Dereferencing Operation
 Dereferencing: Gets/sets value pointed by a pointer
o Assignment Operation
 Assignment: Assign value of one pointer or address of variable to another
pointer of the same type
 Dereferencing can also be used to set values at memory location pointed by
pointer
o Add and Minus Operations
 We can add an integer value c to a pointer, it increases the address by
sizef(data_type)*c
 The size of the pointer matters in this case
o Increase and Decrease Operations
 Pointers support increase and decrease by adding/subtracting an integer value k
 Operation will increase/decrease address value by k times the size of the data
type of the pointer
 Unary increment (++) and decrement (--) are supported
 Note: Amount of increment/decrement is determined by size of pointer type
o Comparison Operations
 Pointer comparisons are supported by using relational operators
 Special Pointers:
o Null Pointers
 Null Pointer: Pointer value for not pointing anywhere
 Good programming practice to set NULL to pointer if you don't have a target to
point
o Generic Pointers
 Generic Pointer: Pointer that has void type; can point at a variable of any type
 Needs to be casted to a specific type when doing operations and
dereferencing
 Syntax: void *ptr;
o Pointers to Pointers
 Pointer to Pointer: Pointer set to point to another pointer
 To declare, add * for each level of reference
 Pointer Pros and Cons:

Pros Cons
Alternative way to access and operate data Difficult concept
Help to output multiple values from function Error prone, difficult to debug
through pass-by-reference
Cahn point to functions and pass function Uninitialized/wrong points cause
references to another function segmentation fault
Support dynamic memory allocation for data Dynamically allocated memory blocks need
objects to be freed explicitly to avoid memory leak
Increase program execution on data processing
Provide efficient tools for manipulating data
structures

Memory Allocations in C
 Static Memory Allocation: Memory allocation done by declaration of global/static variables
o At compile time, global/static variable allocated memory block with relative address to
data region
o At runtime, statically allocated memory blocks are instanced with absolute addresses in
data region
o Size of data region determined by sum of sizes statically allocated memory blocks at
compile time and won’t be changes at runtime
 Automatic Memory Allocation: Memory allocation done by function arguments/local variables
o At compile time, local/argument variable assigned memory block with relative address
to function scope
o At runtime, memory block of automatic allocation is put in stack region when function is
called and automatically released when function is finished
o Automatic release = memory release managed by program execution mechanism, not
program statements
 Dynamic Memory Allocation: Memory allocation done by stdlib library funciton malloc()
o Memory block of dynamic allocation located in heap region; won’t be released
o Dynamically allocated memory block scan be shared by different functions
o Use free() function to release memory block

Arrays
Operations
 Arrays: Data structure that stores collection of data items of the same type in contiguous
memory locations
Used to:
o Store application data records
o Store strings
o Implement other data structures (e.g. Queues, stacks, heaps, hash tales)
o Implement mathematical vectors, matrices, and rectangular tables
 Static Method/Arrays: Allocates memory block in data/stack region at compile time
 Dynamic Method/Arrays: Uses stdlib function malloc() to allocate memory space for array
 Array Pointer: Pointer pointing to an array
o Declaration Syntax: data_type (*ptr_name)[k];
o If pointer ptr holds address of array element, ptr++ represents next element
 Pointer Array (aka Array of Pointers): Array of pointer type elements
o Declaration Syntax: data_type *ptr_array_name[k];
 Passing arrays to functions:
1. Passing by data values
 Value of array element is copied to function
 Array element won't be changed by function
2. Passing by element reference (address at runtime)
 Address of array is copied into function
 Through address, array element can be accessed and changed
3. Passing array by name (i.e. Passing address of the first element)
 Passing array address to function
 Application of arrays:
o Store collection of data items of the same type when maximum number of data items
are known and random access used in application
o Implement mathematical vectors, matrices, and other rectangular tables
o Implement other data structures like string, queues, stacks, hash tables, heaps
o Databases to store data tables
Array Data Structures
 4 reasons why arrays are used to represent and store data in applications:
o Data objects (aka records) to be presented have the same type
o Maximum number of data records is known
o Many random access operations in applications
o Data objects have regular relationship like vector, table, and matrix
 Array data structures stores sequence of data
 Basic array data structure operations:
o Traverse: Access/visit every data record in the array
o Search: Find data record in the array by key value
o Insert: Add new data record in array
o Delete: Remove data record from array
o Merging two arrays
o Sort: Rearrange data records in ascending/descending order

String & String Processing


 String: Sequence of non-null characters followed by null character
 Null character: Character with ASCII code 0, represented by "\0"
 Length: Number of non-null characters
 Array of Strings: Sequence of strings stored in 2D char array
o Declared and initialized with a list of string expressions
 String operations:
1. Read string from stdin
 stdin: Standard input device, default to be keyboard
 If we know max length of string we can declare array size of the max length
 stdio provides three functions to get input from keyboard:
1. scanf(): Get formatted data, prompt user to type string and hit enter to
terminate input
 Inserts typed character one after another into array str starting
from location str[0]; inserts '\0' at the end
 Example: scanf("%s", str);
2. gets(): Get a string, prompts user to type string and hit enter key to
terminate input
 Inserts typed character one after another into array str starting
from location str[0]; inserts '\0' at the end
 Example: gets(str);
3. getchar(): Get and return a character
 Example: str[0] = getchar();
2. Write string to stdout
 stdout: Represents the screen
 putchar(char): Prints single character to screen
 Algorithm -> Traverse string and write each character to stdout and stop when
null is encountered
3. Get length of string
 Algorithm -> Increase counter by 1 for each non-null character
4. Copy Strings
 Algorithm -> Traverse source string and copy character to destination array; add
null at the end
5. Compare two strings
 Algorithm to compare two strings s1 and s2:
o If s1 and s2 are equal, return 0
o else if s1 > s2, namely s1 will come after s2 in dictionary order (i.e.,
lexical order), return 1
o else, namely, s1 < s2, s1 precedes s2 in dictionary order, return -1

Structures, Unions, Enumerations


Structures
 Structure: User-defined data type consisting of list of variables of various data types stored in
contiguous memory blocks
o Size of structure is sum of sizes of all its elements (member's data types)
o Composite data structure, combining different types of data values
 Record: Another name for structure type of data object
 struct: Keyword to define a structure type
 Structure definition doesn't allocate memory; it defines a template that tells compiler the
memory layout of the structure and details of its members
 typedef: Define name for data type
typdef can:
o rename existing data type
o define new type name
 Initializing structure variable = assigning some constants to members of structure variable
 Nested Structure: Structure that contains another structure
 Structure type pointers can be declared to hold address of structure type variable
 Use point-to operator -> to access members of structure variable
 Self-referential Structures: Structures that contain a pointer variable of its own type
 Structure vs. Arrays:

Similarities vs. Differences Structures Arrays


Same -> Memory Hold data objects in contiguous memory locations
Different -> Data types and Can have different data All elements have the
access types same data type
Members accessed by Elements accessed by
their names index
Different -> Value Support value Don’t support whole
assignment assignment array value assignment
Different -> Return Support value return Don’t support whole
array return
Different -> Passing variable Copies structure value Copies address of array
name to functions into function to function

Unions
 Union: User-defined data type that can hold any variable of a given set of member variables at
the same memory location
o Can hold different types of values, but only one value at a time
 Size of union is maximum size of its member types
 Unions vs. Structures

Similarities vs. Differences Unions Structures


Different -> Memory Same memory location Each variable has its won
for all member values, so memory location, so it
it can only hold one data can hold all variable data
member at a time simultaneously
Same -> Operation support Support assignment operations, pointer operations,
passing unions to functions by values/references,
and return types
Same -> Syntax Syntax same; access variable using dot operator

Enumerations
 Enumeration Type: User-defined data type to represent integral constants by symbols/names
o Enumeration type variable stored memory as int type
o sizeof enumeration data type = sizeof(int)
o int operations can be applied to enumeration type
 enum: Keyword to define an enumeration type
 Enumeration vs. Macro
o Advantage of enumeration over using #define is enum is a data type and can be used to
declare and do operations on variables
File I/O
 File I/O: Data transfer between computer memory and hard disk
 Data in memory: For processing and short term storage
o When computer turns off, data is gone
 Hard Disks: Long term storage
o Data remains even if computer if off
 File Output: Write data stored in computer memory to hard disk in forms of files so data can be
retrieved using file name
o Save data from memory to files in disk or other media for long term storage
 File Input: Read data from disk into computer memory for processing
 File I/O and OS
o File I/O requires kernel operations of operating systems (OS)
 Writing data files in disks and accessing file data stored in disks need to access
and control disk
 Disk accessing controls managed by OS
 OS provides services for file I/O user application
 OS Services are system calls
o Programming file I/O in C mostly use file I/O functions provided by stdio library
 Programming file I/O in C can directly use OS's system caller BUT C stdio library
provides functions for file I/O
 Stream Buffer: To transfer data between application's memory and file in disk stream buffer is
used as an intermediate buffer holding chunk of file data for batch transferring from/to disk
o File I/O functions do data transfer between application's memory and file stream buffer
o Data transfer between stream buffer and disk is managed by OS
 2 file format types:
1. ASCII File (test file): Stores data as a sequence of characters
2. Binary File (stream file): Stores data as they are in memory blocks
 When fopen() is called with filename and mode, it does the following:
1. Create I/O stream buffer connecting to file
2. Create FILE structure instance
3. Set pointe rbuffer pointing to stream buffer
4. Set curp pointer to beginning position of stream buffer and other fields of FILE structure
instance
5. Return NULL if one of the above operations fails, otherwise return FILE instance address

Data Structures
 Data Structure: Collection of data values of certain types together with a set of specific
operations that can be performed
o Defines how data items are represented, organized, stored in memory, and operated
 Data structure operations used to operate (access, modify, insert, delete) data values in data
structures
 Selecting/designing efficient data structure is a crucial step in algorithm design/implementation,
the steps are:
1. Determine problem data and data representation
2. Determine basic operations that must be supported
3. Determine resource constraints for each operation
4. Select/design data structure that best meets requirements
 Data Item/Object: Value or set of values
o Elementary Item: Data item that doesn't have subordinate data items
o Composite Item: Data item that has subordinate data items
 Record: Group of data items
 Collection of Records: Application of data
 Data structures design involves the following concepts:
o Abstract Data Type
 Abstract Data Type (ADT): Mathematical model for data whose behaviour is
defined by set of values and operations
 Acts as guideline for implementing data type
 Description of logical and mathematical properties of data
 Specifies set of data objects to be represented and operations on data objects
 Focuses on what it is and what it does, not how
 Abstract: Away from the detailed implementations
o Data Type
 Data Type: Implementation of ADT in programming language
 Translates ADT's specification into detailed representation and operations and
syntax of programming language
 Implementation of ADT contains detailed bit pattern representation of data
values and operations on bit patterns
 Data type operations can be implemented by:
 Hardware circuitry as part of computer CPU
 Software implementation where programs interpret bit patterns to
perform operations
 Data Type Categories:
 Native Data Types: Set of data types directly supported by CPU for
manipulating bit pattern as binary numbers
 Primary Data Types: Set of data types supported by program language
o Define how data will be internally represented, stored, and
retrieved from memory
 Structure Data Types: Composite data type consisting of one or more
data members of various types
Three parts:
o Data Part: Contains data values of various data types
o Address Part: Stores runtime data location information of other
data objects
o Atomic Type: Structure data type that contains no address part,
only data items; ceases to be atomic when you load it into
memory
o Abstract Data Structure
 Abstract Data Structure: Specification on representation and operations of
collection of data items
 Data structure can be viewed as implementation of abstract data structure to
represent one or more data values of specific types in program
o Data Structure Operations
 Basic data structure operations:
 Accessing: Get value of any data element in data structure
 Modification: Set value of data element
 Commonly used data structure operations:
 Traversal: Access each data element exactly once
 Searching: Find location of one or more data elements that satisfy given
condition
 Inserting: Add new data element to data structure
 Deleting: Remove particular data element from data structure
 Advanced data structure operations:
 Sorting: Arrange data objects in ascending/descending order of keys
 Merging: Combine two collections of data values into one data structure
o Application Specific Data Structures
 Application algorithm uses data operations on abstract data types/structures
 Application Specific Data Structures: Program to implement algorithm uses
existing data types to implement abstract data types/structures to create
algorithm specific data types/structures so operations can be efficient
 When writing program to implement algorithm, it needs to use primitive data
types to implement abstract data types/structures to create algorithm specific
data types/structures so operations can be done specifically
 Classification of Data Structures:
o Primitive Data Structure: Consist of single data element of primitive data type of
programming language
o Non-primitive Data Structure: Created using primitive data types
 Linear Data Structure: Elements organized/stored in linear order
Can be represented in memory in two different methods:
 Physically Ordered: Two adjacent elements stored adjacently in memory
(e.g. Arrays)
 Virtually Linked: Linear relationship between elements define by links
(e.g. Addresses of next data elements
 Example: arrays, linked lists, queues, stacks
o Non-linear Data Structure: Elements not organized in sequential order; data element
may connect to multiple data elements
 Example: trees, graphs

You might also like