• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
C refresher-v2_ FOCAS Training
 

C refresher-v2_ FOCAS Training

on

  • 1,387 views

FOCAS

FOCAS

Statistics

Views

Total Views
1,387
Views on SlideShare
1,387
Embed Views
0

Actions

Likes
0
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    C refresher-v2_ FOCAS Training C refresher-v2_ FOCAS Training Presentation Transcript

    • (C) 2008 Emertxe Information Technologies (P) Ltd C – Refresher Team Embedded Emertxe Information Technologies (P) Ltd Bangalore
    • (C) 2008 Emertxe Information Technologies (P) Ltd Contents Basic Refresher Functions Basic Input/Output Strings and Program Segments Pointers Pre-Processing User defined datatypes Misc Topics
    • (C) 2008 Emertxe Information Technologies (P) Ltd Linux InternalsLinux InternalsBasic Refresher
    • (C) 2008 Emertxe Information Technologies (P) Ltd Linux InternalsLinux InternalsFundamentals of data storage
    • (C) 2008 Emertxe Information Technologies (P) Ltd Its All About Bits and Bytes Why bits? Representing information as bits Binary/Hexadecimal Byte representations Numbers ANSI data storage Embedded specific data storage Floating point representation
    • (C) 2008 Emertxe Information Technologies (P) Ltd Why Don’t Computers Use Base 10? Base 10 Number Representation Digits (0-9) are symbols Natural representation for financial transactions Floating point number cannot exactly represent $1.20 Even carries through in scientific notation 1.5213 X 104 Implementing Electronically Hard to store ENIAC (First electronic computer) used 10 vacuum tubes / digit Hard to transmit Need high precision to encode 10 signal levels on single wire Messy to implement digital logic functions Addition, multiplication, etc.
    • (C) 2008 Emertxe Information Technologies (P) Ltd Binary Representations Base 2 Number Representation Represent 1521310 as 111011011011012 Represent 1.2010 as 1.0011001100110011[0011]…2 Represent 1.5213 X 104 as 1.11011011011012 X 213 Electronic Implementation Easy to store with bistable elements Reliably transmitted on noisy and inaccurate wires Straightforward implementation of arithmetic functions
    • (C) 2008 Emertxe Information Technologies (P) Ltd Encoding Byte Values Byte = 8 bits Binary 000000002 to 111111112 Decimal: 010 to 25510 Hexadecimal: 0016 to FF16 Base 16 number representation Use characters ‘0’ to ‘9’ and ‘A’ to ‘F’ Write FA1D37B16 in C as 0xFA1D37B Or 0xfa1d37b 0 0 0000 1 1 0001 2 2 0010 3 3 0011 4 4 0100 5 5 0101 6 6 0110 7 7 0111 8 8 1000 9 9 1001 A 10 1010 B 11 1011 C 12 1100 D 13 1101 E 14 1110 F 15 1111 Hex Decim al Binary
    • (C) 2008 Emertxe Information Technologies (P) Ltd Machine Words Machine Has “Word Size” Nominal size of integer-valued data Including addresses Most current machines are 32 bits (4 bytes) Limits addresses to 4GB Becoming too small for memory-intensive applications High-end systems are 64 bits (8 bytes) Potentially address : 1.8 X 10 19 bytes Machines support multiple data formats Fractions or multiples of word size Always integral number of bytes
    • (C) 2008 Emertxe Information Technologies (P) Ltd Word-Oriented Memory Organization Addresses Specify Byte Locations Address of first byte in word Addresses of successive words differ by 4 (32-bit) or 8 (64-bit)
    • (C) 2008 Emertxe Information Technologies (P) Ltd Byte Ordering Big Endian: Sun’s, Mac’s are “Big Endian” machines Least significant byte has highest address Little Endian: Alphas, PC’s are “Little Endian” machines Least significant byte has lowest address Example Variable x has 4-byte representation 0x01234567 Address given by &x is 0x100
    • (C) 2008 Emertxe Information Technologies (P) Ltd ANSI Data Storage Integral Representation char short int long long long Real Number Representation float double
    • (C) 2008 Emertxe Information Technologies (P) Ltd ANSI Standard Type int is supposed to represent a machine's natural word size The size of character is always 1 byte Default signedness of char is compiler dependent 1 byte = sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long)
    • (C) 2008 Emertxe Information Technologies (P) Ltd Embedded Specific Data Storage Non-portability Solution: User typedefs Size utilizations Compiler Dependency Architecture Dependency u8, s8, u16, s16, u32, s32, u64, s64 Non-ANSI extensions bit
    • (C) 2008 Emertxe Information Technologies (P) Ltd Number system Binary Octal Decimal Hexadecimal BCD
    • (C) 2008 Emertxe Information Technologies (P) Ltd Linux InternalsLinux InternalsIntegral & Real value representation
    • (C) 2008 Emertxe Information Technologies (P) Ltd Integral value representation Integrals are stored on a computer in 2's complement form 2's complement: just invert each bits of its positive's binary value and add 1 Mathematically: -k = 2^n - k
    • (C) 2008 Emertxe Information Technologies (P) Ltd Floating point representation IEEE single precision format (32 bits) V = ( -1 )s x 2(E – 127 ) x (1.F) IEEE double precision format (64 bits) V = ( -1 )s x 2(E – 1023) x (1.F) S: 1 E: 11 F: 52 S: 1 E: 8 F: 23
    • (C) 2008 Emertxe Information Technologies (P) Ltd DIU Convert 1.5 into binary form. Convert 0.7 into the binary form.
    • (C) 2008 Emertxe Information Technologies (P) Ltd Linux InternalsLinux InternalsData types, Variables, sizeof
    • (C) 2008 Emertxe Information Technologies (P) Ltd Sizes of all basic datatypes in C 1 byte = sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long) Size of datatypes varies across platforms What is sizeof(int)? Is sizeof(int) same on all platforms
    • (C) 2008 Emertxe Information Technologies (P) Ltd DIU Run the template sizes.c. And see the sizes of all data types
    • (C) 2008 Emertxe Information Technologies (P) Ltd Linux InternalsLinux InternalsPortability issues with data types
    • (C) 2008 Emertxe Information Technologies (P) Ltd Portability issues -1/7 How to achieve software reliability? How can you run 32-bit C source code on an 8-bit CPU, or 8-bit C source code on a 32-bit CPU? Solution: Designing your code with portability in mind from the beginning.
    • (C) 2008 Emertxe Information Technologies (P) Ltd Portability issues – 2/7 Common portability problem with the size of C variables. On most 8-bit and 16-bit CPUs, compilers treat int variables as 16-bit values. But on most 32-bit CPUs, compilers treat int variables as 32- bit values. If any of your software algorithms depend on the size of an int being 16 bits, your software isn't going to run properly on a 32-bit CPU.
    • (C) 2008 Emertxe Information Technologies (P) Ltd Portability issues – 3/7 For example, a 16-bit counter rolls over to 0 after 65,536 increments, but on a 32-bit CPU, this isn't true.
    • (C) 2008 Emertxe Information Technologies (P) Ltd Portability issues – 4/7 C's typedef feature lets you invent a new name for a data type, in addition to the usual int, char, long, etc. On a 16-bit CPU, typedef int signed16; while on a 32- bit CPU you would say typedef short signed16; In both cases, defined a new name for a "signed 16-bit data value." So,now write your source code and declare variables to be signed16 (instead of int), and you'll get a "signed 16-bit data value" on any CPU (8, 16, or 32 bits).
    • (C) 2008 Emertxe Information Technologies (P) Ltd Portability issues – 5/7 typedefs containing new datatypes are defined in header file and included it in your source files. When you invoke your compiler, you can pass in a special symbol to select the proper variable size
    • (C) 2008 Emertxe Information Technologies (P) Ltd Portability issues – 6/7 /* types.h */ #ifdef SMALL_CPU typedef int signed16; /* signed 16-bit value */ typedef long signed32; /* signed 32-bit value */ typedef unsigned int unsigned16; /* unsigned 16-bit value */ typedef unsigned long unsigned32; /* unsigned 32-bit value */ #else typedef short signed16; /* signed 16-bit value */ typedef int signed32; /* signed 32-bit value */ typedef unsigned short unsigned16; /* unsigned 16-bit value */ typedef unsigned int unsigned32; /* unsigned 32-bit value */ #endif
    • (C) 2008 Emertxe Information Technologies (P) Ltd Portability issues – 7/7 In your source file, you would write your code like this... /* source.c */ #include "types.h" signed16 my_var_16; /* this variable is always 16 bits */ signed32 my_var_32; /* this variable is always 32 bits */
    • (C) 2008 Emertxe Information Technologies (P) Ltd Linux InternalsLinux InternalsType, Variable & Function Qualifiers
    • (C) 2008 Emertxe Information Technologies (P) Ltd Signed and Un-signed 2's complement representation Range of data type (Overflow) Type promotion issues Default signed or unsigned?
    • (C) 2008 Emertxe Information Technologies (P) Ltd The Const Qualifier const qualifier Variables value cannot be changed const used when function does not need to change a variable Attempting to change a const variable is a compiler error The addition of a 'const' qualifier indicates that the program may not modify the variable. Such variables may even be placed in read-only storage Since 'const' variables cannot change their value during runtime (at least not within the scope and context considered), they must be initialized at their point of definition
    • (C) 2008 Emertxe Information Technologies (P) Ltd The Const Qualifier... Example: const int i = 5; An alternate form is also acceptable, since the order of type specifiers and qualifiers does not matter: int const i = 5; Order becomes important when composite types with pointers are used: int * const cp = &i; /* const pointer to int */ const int * ptci; /* pointer to const int */ int const * ptci; /* pointer to const int */
    • (C) 2008 Emertxe Information Technologies (P) Ltd The volatile qualifier In embedded/hardware context its very common to read/write hardware registers, which might get changed by external influences. Compiler may not aware of such possibilities and would optimize corresponding read/write. Volatile is exactly to stop that. Any object whose type includes the volatile type qualifier indicates that the object should not be subject to compiler optimizations altering references to, or modifications of, the object. Optimizations that are defeated by using the volatile specifier can be categorized as follows:
    • (C) 2008 Emertxe Information Technologies (P) Ltd The Volatile Qualifier... Optimizations that alter an object's duration; for example, cases where references to the object are shifted or moved to another part of the program. Optimizations that alter an object's locality; for example, cases where a variable serving as a loop counter is stored in a register to save the cost of doing a memory reference. Optimizations that alter an object's existence; for example, loop induction to actually eliminate a variable reference.
    • (C) 2008 Emertxe Information Technologies (P) Ltd The volatile qualifier... An object without the volatile specifier does not force the compiler to perform these optimizations; It indicates that the compiler has the freedom to apply the optimizations depending on program context and compiler optimization level.
    • 38 The register Qualifier Register variables are a special case of automatic variables. Automatic variables are allocated storage in the memory of the computer; however, for most computers, accessing data in memory is considerably slower than processing in the CPU. Registers – CPUs often have small amounts of storage within itself where data can be stored and accessed quickly And hence, these would help better embedded performence. However, register is just a request to the compiler and may not be honoured. Be cautious in its usage!!!
    • (C) 2008 Emertxe Information Technologies (P) Ltd The Inline Qualifier During compilation, the C compiler automatically inlines small functions in order to reduce execution time (smart inlining). Inlining - The compiler inserts the function body at the place the function is called. With the inline keyword you force the compiler to inline the specified function
    • (C) 2008 Emertxe Information Technologies (P) Ltd The Inline Qualifier... Define inline functions in the same source module as in which you call the function Compiler only inlines a function in the module that contains the function definition. When you need to call the inline function from several source modules, you must include the definition of the inline function in each module (for example using a header file).
    • (C) 2008 Emertxe Information Technologies (P) Ltd static and extern static variables and functions Scope Lifetime extern keyword Usage
    • (C) 2008 Emertxe Information Technologies (P) Ltd DIU Run the template volatile.c and novolatile.c , and see the assembly code for both using GCC option -S, as gcc -S volatile.c gcc -S novolatile.c There will be created a file with extension '.s ' , open the file and compare the assembly code for both. Run the templates inline.c, register.c, const.c
    • (C) 2008 Emertxe Information Technologies (P) Ltd Linux InternalsLinux InternalsSimple & compound statements
    • (C) 2008 Emertxe Information Technologies (P) Ltd Linux InternalsLinux InternalsConditional constructs & Loops
    • (C) 2008 Emertxe Information Technologies (P) Ltd Single step if switch
    • (C) 2008 Emertxe Information Technologies (P) Ltd Repetitive steps for While Do - while
    • (C) 2008 Emertxe Information Technologies (P) Ltd Linux InternalsLinux InternalsOperators & its types
    • (C) 2008 Emertxe Information Technologies (P) Ltd Operators All C operators do 2 things Operates on its operands Returns a value
    • (C) 2008 Emertxe Information Technologies (P) Ltd Type casting Type casting ? Why type casting? How to type cast?
    • (C) 2008 Emertxe Information Technologies (P) Ltd Operators types Based on : Number of operands Unary Binary Ternary Operation Arithmetic Logical Relational Assignment Bitwise Language Pointers Misc
    • (C) 2008 Emertxe Information Technologies (P) Ltd Bitwise Play Operators &, |, <<, >>, ^, ~ Operands should be integer type Precedence Operator PrecedenceOperator Precedence ~ << >> & ^ | (H) (L)
    • (C) 2008 Emertxe Information Technologies (P) Ltd Bitwise play...
    • (C) 2008 Emertxe Information Technologies (P) Ltd Bitwise play... Bitwise AND 10012 & 00112 = 00012 To extract the special area in variable by masking that area Bit OR 10012 | 00112 = 10112 Exclusive OR 10012 ^ 00112 = 10102 1’s Complement (Bits 0 will be converted to 1 and vice versa) ~000010102 = 111101012
    • (C) 2008 Emertxe Information Technologies (P) Ltd Bitwise play... Bitwise Shift Operator Shift left(<<) Shift right(>>) x << y = x * 2yx << y = x * 2y x >> y = x / 2yx >> y = x / 2y
    • (C) 2008 Emertxe Information Technologies (P) Ltd Operator Precedence Operators Association Precedence () [] . -> ! ~ ++ -- + - * (Data Type) sizeof * / % + - << >> < <= > >= == != & ^ | && || ? : = += -= *= /= %= &= ^= |= <<= >>= , Left to right. (High) Right to left. Left to right. Left to right. Left to right. Left to right. Left to right. Left to right. Left to right. Left to right. Left to right. Left to right. Left to right. Right to left Left to right. (Low)
    •   56 (C) 2008 Emertxe Information Technologies (P) Ltd DIU Read an int i, read 0 a b 31, read an integer n, and put the (b-a+1) lsb's of n into i[b:a]. (Refer template file bits_copy.c) Read an integer & a number n. Circular right & left shift the integer by n.(Refer the template circular_shift.c) Verify the promotion table using sizeof.
    • (C) 2008 Emertxe Information Technologies (P) Ltd Linux InternalsLinux InternalsType promotion hierarchy
    •   58 (C) 2008 Emertxe Information Technologies (P) Ltd All will be promoted to signed int Promotion Type Promotion Hierarchy
    • (C) 2008 Emertxe Information Technologies (P) Ltd Linux InternalsLinux InternalsProblems in mixing data types
    • (C) 2008 Emertxe Information Technologies (P) Ltd Linux InternalsLinux InternalsUnderflows & Overflows
    • (C) 2008 Emertxe Information Technologies (P) Ltd Short-Circuit Logical Operators These operators are similar to the & and | operators that are applied to boolean type, and have the ability to “short circuit” a calculation if the result is definitely known, this can improve efficiency AND operator && If one operand is false, the result is false. OR operator || If one operand is true, the result is true.
    •   62 (C) 2008 Emertxe Information Technologies (P) Ltd DIU Run the template file Logical.c. And feel the short circuit operation
    • (C) 2008 Emertxe Information Technologies (P) Ltd Linux InternalsLinux InternalsArray Basics
    • (C) 2008 Emertxe Information Technologies (P) Ltd Array Basics Arrays ? Why we need arrays? Definition Memory calculation Memory layout Accessing the elements using the subscript
    • (C) 2008 Emertxe Information Technologies (P) Ltd Functions Why Functions? Divide & conquer Modularization Re-usability Easy to understand, modify & debug
    • (C) 2008 Emertxe Information Technologies (P) Ltd Need for function prototype Parameters, Args, return values Need for prototype Gives specific information to the compiler Like No. Of args passed Type of the argument Return type.
    • (C) 2008 Emertxe Information Technologies (P) Ltd Function stack
    • (C) 2008 Emertxe Information Technologies (P) Ltd Parameter passing mechanisms Pass by value Pass by reference DIU : WAP function which computes both addition & multiplication of two nos.
    • (C) 2008 Emertxe Information Technologies (P) Ltd Passing Arrays Always arrays are passed by reference.
    • (C) 2008 Emertxe Information Technologies (P) Ltd Main & its arguments Int main(void); Int main(int argc, char *argv[]); Int main(int argc, char *argv[], char *env[]);
    • (C) 2008 Emertxe Information Technologies (P) Ltd Variable argument functions Variadic functions? How to access unnamed args. Inside the functions. va_list ap va_start(ap, num) va_arg(ap, datatype) va_end(ap) Declaring the variadic function Inclusion of the header file
    • (C) 2008 Emertxe Information Technologies (P) Ltd Reentrant functions Reentrancy & Reentrant function. Significance of the reentrant function Conditions should be satisfied by the reentrant function Use of global/static variables
    • (C) 2008 Emertxe Information Technologies (P) Ltd Static functions Restricted to the file where they are declared. static can be reuse of the same function name in other files.
    • (C) 2008 Emertxe Information Technologies (P) Ltd Recursive functions recursive function can be defined as a routine that calls itself directly or indirectly. DIU : write a function to compute factorial of a number recursively.
    • (C) 2008 Emertxe Information Technologies (P) Ltd Inline functions During compilation function call is replaced by the inline function reducing function call overhead. Type checking in performed. When not to make the function inline?
    • (C) 2008 Emertxe Information Technologies (P) Ltd ISR's Callback function Jitter Dos & Donts First Half and Second Half
    • (C) 2008 Emertxe Information Technologies (P) Ltd Linux InternalsLinux InternalsStrings & Program segments
    • (C) 2008 Emertxe Information Technologies (P) Ltd Strings Strings : Array of characters. Low level in nature C does not support string as a data type Library support available Example: “Robert” “B” “” “1456”
    • (C) 2008 Emertxe Information Technologies (P) Ltd Initialization Methods of strings char name[ ] = “Bosch”; char name[6] = “Bosch”; char name[5] = “Hai”; char name[10] = { 'h', 'a', 'i', '0'}; char *msg = “hello”; Memory allocation for strings Difference between above two.
    • (C) 2008 Emertxe Information Technologies (P) Ltd String manipulation Library functions strlen, strcat, strcpy, strcmp, strcasecmp, strncpy, strtok, strdup etc Defined in string.h DIU : Implement strcasecmp() function
    • (C) 2008 Emertxe Information Technologies (P) Ltd Linux InternalsLinux InternalsThe Program Segments
    • (C) 2008 Emertxe Information Technologies (P) Ltd Program segments
    • (C) 2008 Emertxe Information Technologies (P) Ltd Effect Of Different Compiler Consider the following code char *arr = “Hello World”; main() { arr[1] = 'i'; printf(“%s”, arr); } Code copiled using GCC on Linux, will give an error can not modify the code segment. Because, while compiling, the string “Hello World” stored in the code segment, which is read only But compiling with Turbo C, there will not be error.
    • (C) 2008 Emertxe Information Technologies (P) Ltd Placement of Various Segment With Reference to Microcontroller Why we need to know about segment levels: Architecture and Memory placement Loader, Compiler initialization In case of a microcontroller all program instructions (Code segment) are stored in flash memory All the static and global variables (Data Segment) are stored in RAM. All the function items and local variable(Stack Segment) are stored in RAM. Note: Contents mentioned in the slide may not apply to all controllers and may depend on the OS installed
    • (C) 2008 Emertxe Information Technologies (P) Ltd Placement of Various Segment With Reference to Microcontroller... Global and static variable are initialized to zero by default. Loader( not compiler) initializes the whole of BSS to zero. But in case of microcontroller it is compiler's responsibility to initialize the variables to zero, because in a microcontroller the loader may be unavailable.
    • (C) 2008 Emertxe Information Technologies (P) Ltd Constant & Shared Strings char *s1 = “ Hello”; char *s2 = “ Hello”; if(s1 == s2) { printf(“shared”); } else { printf(“Not shared”); }
    • (C) 2008 Emertxe Information Technologies (P) Ltd Pointers The Jargon Memory Locations and its Address 7 Rules of Pointers Points to Know
    • (C) 2008 Emertxe Information Technologies (P) Ltd What's a Jargon? Jargon may refer to terminology used in a certain profession, such as computer jargon, or it may refer to any nonsensical language that is not understood by most people. Speech or writing having unusual or pretentious vocabulary, convoluted phrasing, and vague meaning. Pointer are perceived difficult Because of jargonification So, let's dejargonify & undertsand them Through the 7 Rules The Jargon
    • (C) 2008 Emertxe Information Technologies (P) Ltd Memory Locations and its Address
    • (C) 2008 Emertxe Information Technologies (P) Ltd Rule 1 - Pointer is an Integer Rule 2 - Referencing and De-referencing Rule 3 - Pointer Type Rule 4 - Pointer means Containing Rule 5 - Pointing to Nothing Rule 6 - Pointer Arithmetic Rule 7 - Static vs Dynamic Allocation 7 Rules of Pointers
    • (C) 2008 Emertxe Information Technologies (P) Ltd Whatever we put in data bus is Integer Whatever we put in address bus is Pointer So, at concept level both are just numbers. May be of different sized buses Rule: “Pointer is an Integer” Exceptions: May not be address and data bus of same size Rule 2 Pointers Rule 1
    • (C) 2008 Emertxe Information Technologies (P) Ltd Pointers Rule 2
    • (C) 2008 Emertxe Information Technologies (P) Ltd Pointers Rule 3 So, why do we need types attached to pointers? Only for 'De-referencing' Summarized as the following rule: Rule: “Pointer of type t = t Pointer = (t *) = A variable, which contains an address, which when dereferenced returns a variable of type t, starting from that address”
    • (C) 2008 Emertxe Information Technologies (P) Ltd Pointers Rule 4 Rule: “Pointer pointing to a Variable = Pointer contains the Address of the Variable, i.e. Pointing means Containing” Int *p; int a = 5; p=&a;
    • (C) 2008 Emertxe Information Technologies (P) Ltd Pointers Rule 5 Need for Pointing to 'Nothing' Terminating Linked Lists Indicating Failure by malloc, ... Solution Need to reserve one valid value Which valid value could be most useless? In wake of Oses sitting from the start of memory, 0 is a good choice Rule: “Pointer value of NULL or Zero = Null Addr = Null Pointer = Pointing to Nothing”
    • (C) 2008 Emertxe Information Technologies (P) Ltd Pointers Rule 5 Need for Pointing to 'Nothing' Terminating Linked Lists Indicating Failure by malloc, ... Solution Need to reserve one valid value Which valid value could be most useless? In wake of Oses sitting from the start of memory, 0 is a good choice Rule: “Pointer value of NULL or Zero = Null Addr = Null Pointer = Pointing to Nothing”
    • (C) 2008 Emertxe Information Technologies (P) Ltd Pointers Array Interpretations Original Big Variable Constant Pointer to the 1st Small Variable in the Big Variable When first interpretation fails than second interpretation comes to picture. The following are the case when first interpretation fails: When we pass array variable as fuction argument When we assign a array variable to pointer variable
    • (C) 2008 Emertxe Information Technologies (P) Ltd Pointers Rule 6 arr + i = &arr[i] Value(arr + i) = Value(arr) + i * sizeof(*arr) Rule: “Value(p + i) = Value(p) + i * sizeof(*p)” Corollaries: p + i = &p[i] *(p + i) = p[i]
    • (C) 2008 Emertxe Information Technologies (P) Ltd Pointers Size of void We need to satisfy the Rule 6 for all pointer type including void*, but we can dereference a void*. So it should atleast behave like a integer, as Rule 1. Hence p+i for a void pointer p should result in the value of p increment by i. For this to satisfy the size(void) in Rule 6 needs to be one.
    • (C) 2008 Emertxe Information Technologies (P) Ltd Pointers Rule 7 Rule: “Static Allocation vs Dynamic Allocation” Named vs Unnamed Allocation = Named/Unnamed Houses Managed by Compiler vs User Done internally by Compiler vs Using malloc/free Dynamic corresponding of a 1-D Static Array char c[10]; char *c; c = (char *)(malloc(10 * sizeof(char))); // Must do Use either as *(c + i) or c[i] free(c); // Must do when done using the malloc'ed memory
    • (C) 2008 Emertxe Information Technologies (P) Ltd Pointers 2D Arrays Each Dimension could be Static, or Dynamic Various Forms for 2-D Arrays (2x2 = 4) Both Static (Rectangular) First Static, Second Dynamic First Dynamic, Second Static Both Dynamic 2-D Arrays using a Single Level Pointer
    • (C) 2008 Emertxe Information Technologies (P) Ltd Pointers Both Dimentions Static (Rectangular) Rectanguar array int rec [5][6]; Takes totally 5 * 6 * sizeof(int) bytes
    • (C) 2008 Emertxe Information Technologies (P) Ltd Pointers First Static and Second Dynamic One dimension static, one dynamic (Mix of Rectangular & Ragged) int *ra[5]; for( i = 0; i < 5; i++) ra[i] = (int*) malloc( 6 * sizeof(int)); total memory used : 5 * sizeof(int *) + 6 * 5 * sizeof(int) bytes
    • (C) 2008 Emertxe Information Technologies (P) Ltd Pointers Second Static and First Dynamic int (*ra)[6]; (Pointer to array of 6 integer) ra = (int(*)[6]) malloc( 5 * sizeof(int[6])); total memory used : sizeof(int *) + 6 * 5 * sizeof(int) bytes
    • (C) 2008 Emertxe Information Technologies (P) Ltd Pointers Both Dimensions Dynamic Ragged array int **ra; ra = (int **) malloc (5 * sizeof(int*)); Takes 5 * sizeof(int*) for first level of indirection for(i = 0; i < 5; i++) ra[i] = (int*) malloc( 6 * sizeof(int)); total memory used : 1 * sizeof(int **) + 5 * sizeof(int *) + 5 * 6 * sizeof(int) bytes
    • (C) 2008 Emertxe Information Technologies (P) Ltd Pointers Points to Know Const Qualifier Dangling Pointer Memory Leaks
    • (C) 2008 Emertxe Information Technologies (P) Ltd Pointers DIU What does *p++ do? Does it increment p or the value pointed by p? What is a NULL pointer? How is it different from an unitialized pointer? How is a NULL pointer defined? What is a null pointer assignment error? Does an array always get converted to a pointer? What is the difference betweenarr and &arr? How does one declare a pointer to an entire array? Is the cast to malloc() required at all? What does malloc() , calloc(), realloc(), free() do? What are the common problems with malloc()? Is there a way to find out how much memory a pointer was allocated? What's the difference between const char *p, char * const p and const char * const p?
    • (C) 2008 Emertxe Information Technologies (P) Ltd Pointers DIU What is a void pointer? Why can't we perform arithmetic on a void * pointer? What do Segmentation fault, access violation, core dump and Bus error mean? What is the difference between an array of pointers and a pointer to an array? What is a memory leak? What is a dangling pointer? What do pointers contain? Is *(*(p+i)+j) is equivalent to p[i][j]? Is num[i] == i[num] == *(num + i) == *(i + num)? What operations are valid on pointers? When does one get the Illegal use of pointer in function error?
    • (C) 2008 Emertxe Information Technologies (P) Ltd User defined datatypes Enum Structure Union Typedef Bitfields
    • (C) 2008 Emertxe Information Technologies (P) Ltd Linux InternalsLinux InternalsCompiler stages and preprocessing
    • (C) 2008 Emertxe Information Technologies (P) Ltd W.R.T GNU C Compiler Compiler (gcc): 'G'NU 'C' 'C'ompiler Compiler Stages & Relevant Options: gcc -c Lexical Analyzer Semantic Parser Preprocessor Intermediate Code Generator Assembler Linker gcc -E gcc -S gcc
    • Separate Compilation 112 A C program consists of source code in one or more files Each source file is run through the preprocessor and compiler, resulting in a file containing object code Object files are tied together by the linker to form a single executable program Source code file1.c Object code file1.o Source code file2.c Object code file2.o Libraries Executable code a.out Preprocessor/ Compiler Preprocessor/ Compiler Linker Source code file1.c
    • Preprocessing Preprocessing Occurs before program compiled Inclusion of external files Definition of symbolic constants Macros Conditional compilation Conditional execution All directives begin with # Can only have whitespace before directives Directives not C statements Do not end with ;
    • The Preprocessor The preprocessor takes your source code and – following certain directives that you give it – tweaks it in various ways before compilation. A directive is given as a line of source code starting with the # symbol The preprocessor works in a very crude, “word- processor” way, simply cutting and pasting . it doesn’t really know anything about C! Your source code Preprocessor Enhanced and obfuscated source code Compiler Object code
    • (C) 2008 Emertxe Information Technologies (P) Ltd The #include Preprocessor Directive #include directive Puts copy of file in place of directive Seen many times in example code Two forms #include <filename> For standard library header files Searches predesignated directories #include "filename" Searches in current directory Normally used for programmer-defined files
    • (C) 2008 Emertxe Information Technologies (P) Ltd The #include Preprocessor Directive Usage Loading header files #include <stdio.h> Programs with multiple source files Header file Has common declarations and definitions structures, enumerations, function prototypes Extract commonality of multiple program files
    • (C) 2008 Emertxe Information Technologies (P) Ltd The #define Preprocessor Directive Symbolic constants #define Symbolic constants Constants represented as symbols When program compiled, all occurrences replaced Format #define identifier replacement-text #define PI 3.14159 Everything to right of identifier replaces text #define PI =3.14159 Replaces PI with "=3.14159" Probably an error Cannot redefine symbolic constants
    • (C) 2008 Emertxe Information Technologies (P) Ltd The #define Preprocessor Directive Symbolic constants Advantages Takes no memory Disadvantages Name not be seen by debugger (only replacement text) Do not have specific data type const variables preferred
    • (C) 2008 Emertxe Information Technologies (P) Ltd Preprocessor Directive: Macros Macro Operation specified in #define Intended for legacy C programs Macro without arguments Treated like a symbolic constant Macro with arguments Arguments substituted for replacement text Macro expanded Performs a text substitution No data type checking
    • (C) 2008 Emertxe Information Technologies (P) Ltd Preprocessor Directive: Macros... Example #define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) ) area = CIRCLE_AREA( 4 ); becomes area = ( 3.14159 * ( 4 ) * ( 4 ) ); Use parentheses Without them, #define CIRCLE_AREA( x ) PI * x * x area = CIRCLE_AREA( c + 2 ); becomes area = 3.14159 * c + 2 * c + 2; which evaluates incorrectly
    • (C) 2008 Emertxe Information Technologies (P) Ltd Preprocessor Directive: Macros... Multiple arguments #define RECTANGLE_AREA( x, y ) ( ( x ) * ( y ) ) rectArea = RECTANGLE_AREA( a + 4, b + 7 ); becomes rectArea = ( ( a + 4 ) * ( b + 7 ) ); #undef Undefines symbolic constant or macro Can later be redefined
    • (C) 2008 Emertxe Information Technologies (P) Ltd Conditional Compilation Control preprocessor directives and compilation Cannot evaluate cast expressions, sizeof, enumeration constants Structure similar to if #if !defined( NULL ) #define NULL 0 #endif Determines if symbolic constant NULL defined If NULL defined, defined( NULL ) evaluates to 1 #define statement skipped Otherwise #define statement used Every #if ends with #endif
    • (C) 2008 Emertxe Information Technologies (P) Ltd Conditional Compilation Otherwise #define statement used Every #if ends with #endif Can use else #else #elif is "else if" Abbreviations #ifdef short for #if defined(name) #ifndef short for #if !defined(name)
    • (C) 2008 Emertxe Information Technologies (P) Ltd Conditional Compilation... Comment out “Commented” code Cannot use /* ... */ with C-style comments Cannot nest /* */ Instead, use #if 0 code commented out #endif To enable code, change 0 to 1
    • (C) 2008 Emertxe Information Technologies (P) Ltd Conditional Compilation... Debugging with Debug Code always preserved Even in Production Software #define DEBUG 1 #ifdef DEBUG ... #endif Defining DEBUG enables code After code corrected Remove #define statement Debugging statements are now ignored
    • (C) 2008 Emertxe Information Technologies (P) Ltd The #error Preprocessor Directives #error tokens Typically used to stop unwanted compilation Code for 1 architecture & Compiling for another unsupported 1 Expected a token to be mandatorily defined, but not done so Tokens are groups of characters separated by spaces #error 1 - Out of range error has 6 tokens Compilation may stop (depends on compiler)
    • (C) 2008 Emertxe Information Technologies (P) Ltd #pragma #pragma tokens Action depends on compiler May use compiler-specific options May pass options to later stages of compilation Typically architecture & compiler dependent Unrecognized #pragmas are ignored Specially needed in Embedded Systems to control low-level specifics
    • (C) 2008 Emertxe Information Technologies (P) Ltd The # and ## Operators # operator Replacement text token converted to string with quotes #define PRINT(expr) printf(#expr “= %d”, expr); int num = 10; PRINT(num); will print num = 10 ## operator Concatenates two tokens #define TOKENCONCAT( x, y ) x ## y TOKENCONCAT( O, K ) becomes OK
    • (C) 2008 Emertxe Information Technologies (P) Ltd Predefined Symbolic Constants Five predefined symbolic constants Cannot be used in #define or #undef
    • (C) 2008 Emertxe Information Technologies (P) Ltd 130 DIU How should we write a multistatement macro? How can I write a macro which takes a variable number of arguments? What is the token pasting operator and stringizing operator in C? Define a macro called SQR which squares a number. What should go in header files? How to prevent a header file being included twice? Is there a limit on the number of characters in the name of a header file?
    • (C) 2008 Emertxe Information Technologies (P) Ltd 131 DIU Build the templates string_concatenate.c, debug.c, cube.c, ifdef.c, sqr_x.c, time.c, processor.c, include.c. Then, execute them individually, and observe
    • (C) 2008 Emertxe Information Technologies (P) Ltd 132 Exceptions Divide by zero Floating point exception Memory leaks & Segmentation fault Bus error Stack Overflow
    • (C) 2008 Emertxe Information Technologies (P) Ltd 133 ELF Format Each ELF file is made up of one ELF header, followed by file data. The file data can include: Program header table, describing zero or more segments Section header table, describing zero or more sections Data referred to by entries in the program header table or section header table
    • (C) 2008 Emertxe Information Technologies (P) Ltd 134 ELF Format
    • (C) 2008 Emertxe Information Technologies (P) Ltd 135 Coding guidelines Variable Names Use variable names with a clear meaning in the context of the program whenever possible. Indentation & format Include adequate white-space in the program to improve readability. Insert blank lines to group sections of code. Use indentation to improve readability of control flow. Avoid confusing use of opening/closing braces.
    • (C) 2008 Emertxe Information Technologies (P) Ltd 136 Coding guidelines Internal comments Main program comments should describe overall purpose of the program. You should have a comment at the beginning of each source file describing what that file contains/does. Function comments should describe their purpose and other pertinent information, if any. Compound statements (control flow) should be commented. Finally, see that commenting is not overdone and redundant.
    • (C) 2008 Emertxe Information Technologies (P) Ltd 137 Coding guidelines Modularity In Designing Avoid accomplishing too many tasks in one function; use a separate module (Split your code into multiple logical functions). Also, avoid too many lines of code in a single module; create more modules. Design should facilitate individual module testing. Use automatic/local variables instead of external variables whenever possible. Use separate header files and implementation files for unrelated functions.
    • (C) 2008 Emertxe Information Technologies (P) Ltd 138 Makefile • A makefile is a file (script) containing : – Project structure (files, dependencies) – Instructions for files creation • The make command reads a makefile, understands the project structure and makes up the executable • Makefile mechanism not limited to C programs
    • (C) 2008 Emertxe Information Technologies (P) Ltd 139 Makefile (Project Structure) Project structure and dependencies can be represented as a graph For example Program contains 5 files main.c, median.h, median.c, sort.h, sort.c
    • (C) 2008 Emertxe Information Technologies (P) Ltd 140 Makefile (Dependency Graph) If median.c is edited - gcc -c median.c - gcc median.o main.o sort.o –o top
    • (C) 2008 Emertxe Information Technologies (P) Ltd Makefile Syntax
    • (C) 2008 Emertxe Information Technologies (P) Ltd Makefile Example
    • (C) 2008 Emertxe Information Technologies (P) Ltd Thank You !