Published on

C Programmer Tutorial

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. C Programming <ul><li>A computer needs to be programmed to solve a problem. </li></ul><ul><ul><li>C is a programming language developed at AT&T bell labs. </li></ul></ul><ul><ul><li>Any programming Language can be divided in to two categories. </li></ul></ul><ul><ul><li>Problem oriented (High level language) </li></ul></ul><ul><ul><li>Machine oriented (low level language) </li></ul></ul><ul><ul><li>C is considered as a middle level Language. </li></ul></ul><ul><ul><li>C is modular,portable,reusable </li></ul></ul><ul><ul><li>C is a language of few words that are known as keyword. </li></ul></ul><ul><ul><li>C code can be written in routines called function </li></ul></ul><ul><ul><li>Algorithm: to understand about the program </li></ul></ul><ul><ul><li>C is famous because reliable,simple,easy </li></ul></ul><ul><ul><li>Compactness,generality,efficiency,modularity and simplicity </li></ul></ul>
  2. 2. Preparing to program <ul><ul><li>(1)Determine the objective of the program. </li></ul></ul><ul><ul><li>Determine the methods you want to use . </li></ul></ul><ul><ul><li>Create the program to solve the problem </li></ul></ul><ul><ul><li>Run the program for output </li></ul></ul>
  3. 3. Feature of C Program <ul><li>Structured language </li></ul><ul><li>General purpose language </li></ul><ul><li>Portability </li></ul><ul><li>Code Re usability </li></ul><ul><li>Ability to customize and extend </li></ul><ul><li>Limited Number of Key Word </li></ul>
  4. 4. Structured Language <ul><li>It has the ability to divide and hide all the information and instruction. </li></ul><ul><li>Code can be partitioned in C using functions or code block. </li></ul><ul><li>C is a well structured language compare to other. </li></ul>
  5. 5. Portability <ul><li>Portability is the ability to port or use the software written . </li></ul><ul><li>One computer C program can be reused. </li></ul><ul><li>By modification or no modification. </li></ul>
  6. 6. General Purpose Language <ul><li>Make it ideal language for system programming. </li></ul><ul><li>It can also be used for business and scientific application. </li></ul><ul><li>ANSI established a standard for c in 1983. </li></ul><ul><li>The ability of c is to manipulate bits,byte and addresses. </li></ul><ul><li>It is adopted in later 1990. </li></ul>
  7. 7. Code Re usability and Ability to Customize and Extend <ul><li>A programmer can easily create his own function </li></ul><ul><li>It can can be used repeatedly in different application </li></ul><ul><li>C program basically collection of function </li></ul><ul><li>The function are supported by 'c' library </li></ul><ul><li>Function can be added to 'c' library continuously </li></ul>
  8. 8. Limited number of keywords and unix library function <ul><li>There are only 32 keywords in 'C' </li></ul><ul><li>27 keywords are given by ritchie </li></ul><ul><li>5 is added by ANSI </li></ul><ul><li>the strength of 'C' is lies in its in-built function </li></ul><ul><li>unix system provides as large number of C function </li></ul><ul><li>some function are used in operation . </li></ul><ul><li>other are for specialized in their application </li></ul>
  9. 9. 'C' program structure <ul><li>Pre-processor directives </li></ul><ul><li>Global declarations </li></ul><ul><li>Main( ) </li></ul><ul><li>{ </li></ul><ul><li>Local variable deceleration </li></ul><ul><li>Statement sequences </li></ul><ul><li>Function invoking </li></ul><ul><li>} </li></ul>
  10. 10. Writing,compiling and executing <ul><li>Program need to be compiled before execution </li></ul><ul><li>'C' is case sensitive </li></ul><ul><li>Linking is the process of joining other program files </li></ul><ul><li>All keywords are lowercased </li></ul><ul><li>C is case sensitive </li></ul><ul><li>Keywords cannot be used for any other purpose </li></ul><ul><li>C statement always ends with a semicolon </li></ul><ul><li>No blank spaces are allowed with in a variable,constant or keyword </li></ul><ul><li>File should be have the extension .c </li></ul>
  11. 11. Recap of previous session <ul><li>Introduction to programming </li></ul><ul><li>Features of 'C' </li></ul><ul><li>Writing,Compiling,Linking and executing </li></ul><ul><li>Writing a 'C' program </li></ul>
  12. 12. Introduction <ul><li>Data types are used to declare a variety of different values. </li></ul><ul><li>Variables are important tool of a programmer </li></ul><ul><li>They are used to keep account of various values . </li></ul><ul><li>Like in a game ,weight or height of the player etc </li></ul>
  13. 13. Data types <ul><li>Variable is an identifier </li></ul><ul><li>Variable must be declared before it is used in the program </li></ul><ul><li>'C' has 5 basic built-in data types </li></ul><ul><li>'C' supports aggregates data types </li></ul><ul><li>Data type defines a set of values that a variable can store along with a set of operations that can be performed on it. </li></ul><ul><li>A variable takes different values at different times </li></ul><ul><li>Modifiers are used to alter the meaning of the base type to fit the needs of various situations more precisely . </li></ul>
  14. 14. 'C' has five basic built in data type <ul><li>Char (character value) </li></ul><ul><li>Int (integer value) </li></ul><ul><li>Float (Floating point value) </li></ul><ul><li>Double (Double floating point value) </li></ul><ul><li>Void (Valueless) </li></ul>
  15. 15. Void is used to <ul><li>Declare explicitly that a function is not returning a value </li></ul><ul><li>Declare explicitly that a function has no parameter </li></ul><ul><li>Create generic pointer </li></ul><ul><li>'C' also supports several aggregate types including structure ,union ,enumeration and user defined types. </li></ul>
  16. 16. Declaring a variable <ul><li>A variable should be declare before it is used in the program </li></ul><ul><li>Example: data-type var-list; </li></ul><ul><li>Data type must be valid data type and var-list may be consist of one or more identifier names separated by commas operator. </li></ul><ul><li>The declaration indicates the compiler about the variable names and types of data </li></ul><ul><li>Example : int count; </li></ul><ul><li>double balance; </li></ul><ul><li>float amount; </li></ul><ul><li>Int, double,and float are keywords and cannot be used as variable names. </li></ul>
  17. 17. Assigning values <ul><li>Values can be assigned to variable using the assignment operator (=). </li></ul><ul><li>var-name=expression; </li></ul><ul><li>An expression can be a single constant or combination of variables,operators and constants. </li></ul><ul><li>Data-type var-name=constant; </li></ul><ul><li>int value=250; </li></ul><ul><li>char name= “salini” </li></ul><ul><li>double amount =76.80 </li></ul>
  18. 18. Type Modifier <ul><li>The basic data types may have various modifiers preceding them except type void. </li></ul><ul><li>A modifier is used to alter the meaning of the base type to fit the needs of various situations more precisely. </li></ul><ul><li>The list of modifier: </li></ul><ul><li>Signed </li></ul><ul><li>Unsigned </li></ul><ul><li>Long </li></ul><ul><li>Short </li></ul>
  19. 19. Character <ul><li>This is a group of 8 data bits. </li></ul><ul><li>'C' represents either a letter of roman alphabet. </li></ul><ul><li>Small integer in the range of 0 through to +255. </li></ul><ul><li>To give a named memory area in which a single letter has to be stored </li></ul><ul><li>Declaration </li></ul><ul><li>char letter; </li></ul>
  20. 20. Integer <ul><li>There are two types of integers </li></ul><ul><li>Short </li></ul><ul><li>Long </li></ul><ul><li>The actual number of bits used in these types is implementation dependent. </li></ul><ul><li>For sixteen bit machine ,the long integer is two machine words long,and short integer is one machine word long. </li></ul><ul><li>short int smaller_number; </li></ul><ul><li>long int big_number; </li></ul>
  21. 21. Real number <ul><li>Float offers two sizes-float and double that are similar to integer type </li></ul><ul><li>Approximately float represents six significant digit and double is twelve. </li></ul><ul><li>float length_of_water_line; </li></ul><ul><li>double displacement; </li></ul>
  22. 22. Signed and unsigned prefixes <ul><li>The deceleration can be preceded by the word unsigned for both the character and integer types which the range so that 0 is the minimum,and the maximum is twice that of the signed data type. </li></ul><ul><li>If the word in memory is going to be used as a bit pattern or a mask and not a number, the use of unsigned is strongly urged. </li></ul><ul><li>The default for the int types is always signed , and char is machine dependent. </li></ul>
  23. 23. Character Set <ul><li>Characters are used to form the words, numbers and expression </li></ul><ul><li>The characters in 'C' are grouped into the following categories: </li></ul><ul><li>character set- alphabets from A....Z,a....z </li></ul><ul><li>All decimal digits from 0.....9 </li></ul><ul><li>Special characters include </li></ul><ul><li>, . ; : ? ' &quot; ! / | ~ - $ </li></ul><ul><li>% # & ^ * _ + < > ( ) { } [ ] blank space </li></ul>
  24. 24. Keywords and Indentifier <ul><li>Every ' C' word is classified as either a keyword or an identifier. </li></ul><ul><li>All identifier have fixed meaning, which can not be changed. </li></ul><ul><li>Rules for identifier </li></ul><ul><li>Legal characters are a-z, A-Z,0-9 and _ </li></ul><ul><li>Case significant </li></ul><ul><li>The first character must be a letter or _ </li></ul><ul><li>Identifier can be of any length </li></ul><ul><li>The reserved keywords should not be used as identifier. </li></ul><ul><li>Valid identifier invalid identifier </li></ul><ul><li>Count . 1count </li></ul><ul><li>Test23 .hi! </li></ul><ul><li>high_bal . high balance </li></ul>
  25. 25. keywords <ul><li>Auto double int struct break </li></ul><ul><li>Long switch case enum register </li></ul><ul><li>Typedef char extern return union </li></ul><ul><li>Float unsigned short continue for </li></ul><ul><li>Signed void default goto sizeof </li></ul><ul><li>Volatile do if static while </li></ul><ul><li>Else const </li></ul>
  26. 26. Constants <ul><li>Supports numerical as well as character constants. </li></ul><ul><li>'C' supports several types of constants. </li></ul><ul><li>'C' has two types of modifier. </li></ul><ul><li>Variable of type const cannot be modified </li></ul><ul><li>Constants are fixed values that do not change during the execution of a program. </li></ul><ul><li>'C' supports both numeric and character constants </li></ul>
  27. 27. C supports several types constant <ul><li>Numeric constant </li></ul><ul><li>Integer constant </li></ul><ul><li>Floating point (real) constant </li></ul><ul><li>Character constant </li></ul><ul><li>Single character constant </li></ul><ul><li>String constant </li></ul><ul><li>The following rules apply to all numeric constant </li></ul><ul><li>Non- digit characters and blanks cannot be included </li></ul><ul><li>Can be preceded by minus sign </li></ul>
  28. 28. Escape sequences <ul><li>Certain non printing characters as well as the backslash () and the apostrophe('), can be expressed in terms of escape sequence. </li></ul><ul><li>Example for new line </li></ul><ul><li>Bell a carriage return </li></ul><ul><li>Backspace  formfeed f </li></ul><ul><li>Horizontal tab quotation mark ” </li></ul><ul><li>Vertical tab v apostrophe ' </li></ul><ul><li>Backslash question mark ? </li></ul><ul><li>Null </li></ul>
  29. 29. Access modifier <ul><li>C has two type modifiers that can be used to control the way in which variables may be accessed or modified. </li></ul><ul><li>These are </li></ul><ul><li>Const </li></ul><ul><li>example const int my_age=39; </li></ul><ul><li>Volatile </li></ul><ul><li>example volatile int date </li></ul>
  30. 30. Operator <ul><li>Three kinds of operators. </li></ul><ul><li>Two types of casting. </li></ul><ul><li>'C' includes a class of operators . </li></ul><ul><li>That act upon a single operand to produce a new value. </li></ul><ul><li>Ternary operator operates on three operands. </li></ul><ul><li>'C' is very rich in built -in operator. </li></ul><ul><li>An operator is a symbol that indicates the compiler to perform specific mathematical or logical manipulation. </li></ul>
  31. 31. Three general classes of operator <ul><li>Arithmetic operator </li></ul><ul><li>Relational operator </li></ul><ul><li>Assignment operator </li></ul><ul><li>Special operators to perform particular task </li></ul><ul><li>Ternary (conditional) operator </li></ul><ul><li>Size of operator </li></ul><ul><li>Comma operator </li></ul><ul><li>& Operator </li></ul><ul><li>. and -> operator </li></ul>
  32. 32. Arithmetic Operators <ul><li>Operator Action Example </li></ul><ul><li>_ Subtraction a-b </li></ul><ul><li>+ Addition a+b </li></ul><ul><li>* Multiplication a*b </li></ul><ul><li>/ division a/b </li></ul><ul><li>% modulus Division a%b </li></ul><ul><li>- Decrement a- or -a </li></ul><ul><li>++ increment a+ or ++ </li></ul>
  33. 33. casting <ul><li>When operand differ in type they may undergo type conversion before the expression takes on its final value. </li></ul><ul><li>The final result will be expressed in the highest precision possible, consistent with data type of the operand. </li></ul><ul><li>There are two types of casting </li></ul><ul><li>Implicit </li></ul><ul><li>Explicit </li></ul>
  34. 34. Implicit casting <ul><li>If either operand is long double, convert the other to long double </li></ul><ul><li>If either operand is double , convert the other to float. </li></ul><ul><li>Convert char and short to int. </li></ul><ul><li>If either operand is long convert the other to long. </li></ul>
  35. 35. Explicit casting <ul><li>The expression can be converted to a different data type if desired data type, enclosed in parentheses </li></ul><ul><li>(data type) expression </li></ul><ul><li>int a+m; </li></ul><ul><li>sqrt ((double)x) </li></ul><ul><li>The cast produces the value of the proper type;x itself is not altered </li></ul>
  36. 36. Linking with math library <ul><li>This is following code links to the math library </li></ul><ul><li>cc -o cast cast.c – lm </li></ul><ul><li>the -l switch stands for 'library' </li></ul><ul><li>The library that is searched in the case is libm.a the path u search that is '/usr/lib' where libm.a is found . </li></ul>
  37. 37. Unary operator <ul><li>'C' include a class of operators that act upon a single operand to produce a new value. </li></ul><ul><li>The most common unary operation is unary minus. </li></ul><ul><li>Example </li></ul><ul><li>-143 -(a+m) </li></ul><ul><li>-12 -3.2 </li></ul>
  38. 38. Increment and Decrement <ul><li>x=x+1; </li></ul><ul><li>x+=1; </li></ul><ul><li>x++; </li></ul><ul><li>x=x-1; </li></ul><ul><li>x-=1; </li></ul>
  39. 39. Postfix and Prefix <ul><li>A postfix expression is obtained by post fixing a++ or – operator </li></ul><ul><li>The value of the expression is the value of the operand. </li></ul><ul><li>x=10; </li></ul><ul><li>y=++x; </li></ul><ul><li>x=10; </li></ul><ul><li>y=x++; </li></ul>
  40. 40. Relational and Logical operator <ul><li>Operator Meaning </li></ul><ul><li>< is less then </li></ul><ul><li><= is less then or equal to </li></ul><ul><li>> is greater then </li></ul><ul><li>>= is greater then or equal to </li></ul><ul><li>== is equal to </li></ul><ul><li>!= is not equal </li></ul><ul><li>&& Logical AND </li></ul><ul><li>|| Logical OR </li></ul><ul><li>! Logical NOT </li></ul>
  41. 41. Conditional (:?) Operator <ul><li>var=exp1?exp2:exp3 </li></ul><ul><li>x=10; </li></ul><ul><li>y=x>9 ?100:200; </li></ul><ul><li>x=10; </li></ul><ul><li>if (x>9) </li></ul><ul><li>{ </li></ul><ul><li>y=100; </li></ul><ul><li>} </li></ul><ul><li>else </li></ul><ul><li>{ </li></ul><ul><li>y=200; </li></ul><ul><li>} </li></ul>
  42. 42. Recap of previous session <ul><li>Data type </li></ul><ul><li>Constants </li></ul><ul><li>Operator </li></ul>
  43. 43. POINTERS <ul><li>Simply stated, a pointer is an address. Instead of being a variable, it is a pointer to a variable stored </li></ul><ul><li>somewhere in the address space of the program. It is always best to use an example so load the file named POINTER.C and display it on your monitor for an example of a program with some pointers in it. </li></ul><ul><li>For the moment, ignore the data definition statement where we define index and two other fields </li></ul>
  44. 44. POINTERS CONT.. <ul><li>beginning with a star. It is properly called an asterisk, but for reasons we will see later, let's agree to call </li></ul><ul><li>it a star. If you observe the statement in line 8, it should be clear that we assign the value of 39 to the </li></ul><ul><li>variable named index. This is no surprise, we have been doing it for several programs now. The </li></ul><ul><li>statement in line 9 however, says to assign to pt1 a strange looking value, namely the variable index with </li></ul>
  45. 45. POINTERS CONT.... <ul><li>An ampersand in front of it. In this example, pt1 and pt2 are pointers, and the variable named index is a simple variable. Now we have a problem similar to the old chicken and egg problem. We need to learn </li></ul><ul><li>how to use pointers in a program, but to do so requires that first we define the means of using the pointers in the program. </li></ul><ul><li>The following two rules will be somewhat confusing to you at first, but we need to state the definitions </li></ul><ul><li>before we can use them. Take your time, and the whole thing will clear up very quickly. </li></ul>
  46. 46. POINTERS <ul><li>TWO VERY IMPORTANT RULES </li></ul><ul><li>The following two rules are very important when using pointers and must be thoroughly understood. </li></ul><ul><li>1. A variable name with an ampersand in front of it defines the address of the variable and therefore points to the variable. . </li></ul><ul><li>2. A pointer with a star in front of it refers to the value of the variable pointed to by the pointer line. </li></ul>
  47. 47. POINTERS <ul><li>Twelve of the program can be read as &quot;The stored (starred) value to which the pointer pt1 points is </li></ul><ul><li>assigned the value 13&quot;. This is commonly referred to as dereferencing the pointer. Now you can see why it is convenient to think of the asterisk as a star, it sort of sounds like the word store. </li></ul><ul><li>MEMORY AIDS </li></ul><ul><li>1. Think of & as an address. </li></ul><ul><li>2. Think of * as a star referring to stored. </li></ul>
  48. 48. NULL POINTERS <ul><li>#include <stdio.h> </li></ul><ul><li>int *ip = NULL; </li></ul><ul><li>if(ip != NULL) </li></ul><ul><li>printf(&quot;%d &quot;, *ip); </li></ul>
  49. 49. NULL POINTERS <ul><li>#include <stddef.h> </li></ul><ul><li>char *mystrstr(char input[], char pat[]) { </li></ul><ul><li>char *start, *p1, *p2; </li></ul><ul><li>for(start = &input[0]; *start != ''; start++) </li></ul><ul><li>{ /* for each position in input string... */ </li></ul><ul><li>p1 = pat; /* prepare to check for pattern string there */ </li></ul><ul><li>p2 = start; </li></ul><ul><li>while(*p1 != ''){ </li></ul><ul><li>if(*p1 != *p2) /* characters differ */ </li></ul><ul><li>break; </li></ul><ul><li>p1++; </li></ul><ul><li>p2++; </li></ul><ul><li>} </li></ul><ul><li>if(*p1 == '') /* found match */ </li></ul><ul><li>return start; </li></ul><ul><li>} </li></ul><ul><li>return NULL; </li></ul><ul><li>} </li></ul>
  50. 50. Equivalence in Array and pointer <ul><li>There are a number of similarities between arrays and pointers in C. If you have an array </li></ul><ul><li>int a[10]; </li></ul><ul><li>you can refer to a[0], a[1], a[2], etc., or to a[i] where i is an int. If you declare a pointer variable ip and set it to point to the beginning of an array: </li></ul><ul><li>int *ip = &a[0]; </li></ul>
  51. 51. Arrays and Pointers as Function Arguments <ul><li>int getline(char *line, int max){ </li></ul><ul><li>int nch = 0; </li></ul><ul><li>int c; </li></ul><ul><li>max = max - 1; /* leave room for '' */ </li></ul><ul><li>#ifndef FGETLINE </li></ul><ul><li>while((c = getchar()) != EOF) </li></ul><ul><li>#else </li></ul><ul><li>while((c = getc(fp)) != EOF) </li></ul><ul><li>#endif{ </li></ul><ul><li>if(c == ' ') </li></ul><ul><li>break; </li></ul><ul><li>if(nch < max){ </li></ul><ul><li>line[nch] = c; </li></ul><ul><li>nch = nch + 1; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>if(c == EOF && nch == 0) </li></ul><ul><li>return EOF; </li></ul><ul><li>line[nch] = ''; </li></ul><ul><li>return nch; </li></ul><ul><li>} </li></ul>
  52. 52. String <ul><li>char internal_string_1[] = &quot;Hello&quot;; </li></ul><ul><li>char internal_string_2[] = &quot;world&quot;; </li></ul><ul><li>char *p1 = &internal_string_1[0]; </li></ul><ul><li>int len = strlen(&internal_string_2[0]); </li></ul>
  53. 53. Preprocessor Directives <ul><li>Preprocessor directives are instructions to the compiler that begin with a # sign. </li></ul><ul><li>Executed before the compilation begin. </li></ul><ul><li>Most frequently used directives </li></ul><ul><li>- #include </li></ul><ul><li>- #define </li></ul>
  54. 54. Notes <ul><li>It instruct s the compiler to include a header file,specified within angled brackets or double quote,after the #include statement into the source code </li></ul><ul><li>A header or a standard library contain a set of related functions,which perform various tasks in a program. </li></ul><ul><li>Header file generally have extension '.h'. </li></ul><ul><li>stdio.h contains a set of console i/o functions </li></ul><ul><li>#include referred to as nested includes. </li></ul><ul><li>The number of nesting varies from compiler to compiler. </li></ul><ul><li>Header files are usually placed in a special library called include . </li></ul><ul><li>If the name of the header file is specified in angled brackets,the file searched for in this directory the file name is enclosed in double quotes,the file is looked for in an implementation-defined manner. </li></ul>
  55. 55. Macros <ul><li>Macro is imperative that there is no space between the macro name and the opening parenthesis. </li></ul><ul><li>#include “stdio.h” #define START 0 /*starting point of loop*/ </li></ul><ul><li>#define ENDING 9 /*Ending point of loop*/ </li></ul><ul><li>#define MAX (A,B) ((A)>(B)?(B):(A)) /*Max macro definition*/ </li></ul><ul><li>#define MIN (A,B) ((A)>(B)?(B):(A)) /*Min macro definition*/ </li></ul><ul><li>main ( ) </li></ul><ul><li>{ </li></ul><ul><li>int index, mn,mx; </li></ul><ul><li>int count = 5 </li></ul><ul><li>. </li></ul><ul><li>mx=max (index,count); </li></ul><ul><li>mn=min(index,count); </li></ul><ul><li>. </li></ul><ul><li>. </li></ul><ul><li>} </li></ul>
  56. 56. Getchar( ) <ul><li>The simplest i/o function to read the input and show the standard output . </li></ul><ul><li>The getchar( ) function reads a single character from the console. </li></ul><ul><li>The function does not require any arguments,through a pair of parentheses must follow the word getchar. </li></ul><ul><li>Example </li></ul><ul><li><var_name>=getchar( ); </li></ul><ul><li>char name; </li></ul><ul><li>name =getchar( ); </li></ul>
  57. 57. Putchar( ) <ul><li>Single character can be written to the terminal using the 'C' library function putchar( ) Example </li></ul><ul><li>putchar (var_name) </li></ul><ul><li>name ='A' </li></ul><ul><li>putchar(name) </li></ul><ul><li>The above putchar ( ) will display the character A on the screen </li></ul>
  58. 58. Printf( ) <ul><li>The printf( )function provides certain features that can be effectively exploited to control the alignment and spacing of prints outs on the terminal. </li></ul><ul><li>printf(“format-string”,arg1,arg2,arg3,......); </li></ul><ul><li>The format -strings defines the way in which the subsequent argument arg1,arg2...are to be displayed. </li></ul><ul><li>The format string consist of two types </li></ul><ul><li>-Character that will be printed on the terminal. </li></ul><ul><li>-format commands that defines the output format of each argument </li></ul><ul><li>Printf(“hello %c %d %s”, 'x', '12', “there!”); </li></ul><ul><li>will display </li></ul><ul><li>hello x 12 there! </li></ul>
  59. 59. Scanf( ) <ul><li>Scanf is used for reading in data from the standard input (keyboard). </li></ul><ul><li>Scanf (“format-string” &arg1,&arg2...); </li></ul><ul><li>The format string may include: </li></ul><ul><li>Field specifier </li></ul><ul><li>Optional field width </li></ul><ul><li>Optional white and non-whit character. </li></ul><ul><li>Example: </li></ul><ul><li>scanf (“%d”, &count); </li></ul>
  60. 60. List all format <ul><li>Code Format </li></ul><ul><li>%c Character </li></ul><ul><li>%d Signed decimal integer </li></ul><ul><li>%i Signed decimal integer </li></ul><ul><li>%e Scientific notation[e] </li></ul><ul><li>%E Scientific notation[E] </li></ul><ul><li>%f Decimal floating point </li></ul><ul><li>%o unsigned octal </li></ul><ul><li>%s String of character </li></ul><ul><li>%u unsigned decimal integer </li></ul><ul><li>%x unsigned Hexadecimal (lower) </li></ul><ul><li>%X unsigned Hexadecimal (upper) </li></ul><ul><li>%p dispaly a pointer </li></ul><ul><li>%% print a % </li></ul>
  61. 61. Mixed data Output <ul><li>It is permitted to mix data types in one printf statement. </li></ul><ul><li>Example </li></ul><ul><li>Printf (“%d%f%s%c, a,b,c,d); </li></ul><ul><li>this is big advantage in the 'C' . </li></ul>
  62. 62. Types <ul><li>The type of a variable determines what kinds of values it may take on. An operator computes new values out of old ones. An expression consists of variables, constants, and operators combined to perform some useful computation. In this chapter, we'll learn about C's basic types, how to write constants and declare variables of these types, and what the basic operators are. </li></ul><ul><li>As Kernighan and Ritchie say, ``The type of an object determines the set of values it can have and what operations can be performed on it.'' This is a fairly formal, mathematical definition of what a type is, but it is traditional (and meaningful). There are several implications to remember. </li></ul>
  63. 63. Types <ul><li>1. The ``set of values'' is finite. C's int type can not represent all of the integers; its float type can not represent all floating-point numbers. </li></ul><ul><li>2. When you're using an object (that is, a variable) of some type, you may have to remember what values it can take on and what operations you can perform on it. For example, there are several operators which play with the binary (bit-level) representation of integers, but these operators are not meaningful for and may not be applied to floating-point operands. </li></ul><ul><li>3. When declaring a new variable and picking a type for it, you have to keep in mind the values and operations you'll be needing. </li></ul><ul><li>In other words, picking a type for a variable is not some abstract academic exercise; it's closely connected to the way(s) you'll be using that variable. </li></ul>
  64. 64. Types cont... <ul><li>There are only a few basic data types in C. The first ones we'll be encountering and using are: </li></ul><ul><li>* char a character </li></ul><ul><li>* int an integer, in the range -32,767 to 32,767 </li></ul><ul><li>* long int a larger integer (up to +-2,147,483,647) </li></ul><ul><li>* float a floating-point number </li></ul><ul><li>* double a floating-point number, with more precision and perhaps greater range than float </li></ul>
  65. 65. Constants A constant is just an immediate, absolute value found in an expression. The simplest constants are decimal integers, e.g. 0, 1, 2, 123 . Occasionally it is useful to specify constants in base 8 or base 16 (octal or hexadecimal); this is done by prefixing an extra 0 (zero) for octal, or 0x for hexadecimal: the constants 100, 0144, and 0x64 all represent the same number. (If you're not using these non-decimal constants, just remember not to use any leading zeroes. If you accidentally write 0123 intending to get one hundred and twenty three, you'll get 83 instead, which is 123 base 8.)
  66. 66. Declaration <ul><li>. You may wonder why variables must be declared before use. There are two reasons: </li></ul><ul><li>1. It makes things somewhat easier on the compiler; it knows right away what kind of storage to allocate and what code to emit to store and manipulate each variable; it doesn't have to try to intuit the programmer's intentions. </li></ul><ul><li>2. It forces a bit of useful discipline on the programmer: you cannot introduce variables willy-nilly; you must think about them enough to pick appropriate types for them. (The compiler's error messages to you, telling you that you apparently forgot to declare a variable, are as often helpful as they are a nuisance: they're helpful when they tell you that you misspelled a variable, or forgot to think about exactly how you were going to use it.) </li></ul>
  67. 67. Function calls <ul><li>printf(&quot;Hello, world! &quot;) </li></ul><ul><li>printf(&quot;%d &quot;, i) </li></ul><ul><li>sqrt(144.) </li></ul><ul><li>Getchar() </li></ul>
  68. 68. Expression statement <ul><li>Most of the statements in a C program are expression statements. An expression statement is simply an expression followed by a semicolon. The lines </li></ul><ul><li>i = 0; </li></ul><ul><li>i = i + 1; </li></ul><ul><li>and </li></ul><ul><li>printf(&quot;Hello, world! &quot;); </li></ul>
  69. 69. If statement <ul><li>if( expression ) </li></ul><ul><li>{ </li></ul><ul><li>statement<sub>1</sub> </li></ul><ul><li>statement<sub>2</sub> </li></ul><ul><li>statement<sub>3</sub> </li></ul><ul><li>} </li></ul>
  70. 70. Boolean expression <ul><li>< less than </li></ul><ul><li><= less than or equal </li></ul><ul><li>> greater than </li></ul><ul><li>>= greater than or equal </li></ul><ul><li>== equal </li></ul><ul><li>!= not equal </li></ul>
  71. 71. While loop <ul><li>int x = 2; </li></ul><ul><li>while(x < 1000) </li></ul><ul><li>{ </li></ul><ul><li>printf(&quot;%d &quot;, x); </li></ul><ul><li>x = x * 2; </li></ul><ul><li>} </li></ul>
  72. 72. For loop <ul><li>for (i = 0; i < 10; i = i + 1) </li></ul><ul><li>printf(&quot;i is %d &quot;, i); </li></ul>
  73. 73. Break and continue <ul><li>#include <stdio.h> </li></ul><ul><li>#include <math.h> </li></ul><ul><li>Main() { </li></ul><ul><li>int i, j; </li></ul><ul><li>printf(&quot;%d &quot;, 2); </li></ul><ul><li>for(i = 3; i <= 100; i = i + 1) </li></ul><ul><li>{ </li></ul><ul><li>for(j = 2; j < i; j = j + 1) </li></ul><ul><li>{ </li></ul><ul><li>if(i % j == 0) </li></ul><ul><li>break; </li></ul><ul><li>if(j > sqrt(i)) </li></ul><ul><li>{ </li></ul><ul><li>printf(&quot;%d &quot;, i); </li></ul><ul><li>break; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>return 0; </li></ul><ul><li>} </li></ul>
  74. 74. Character output <ul><li>The library function putc ( ) writes a single character to a specified stream. Its prototype, in stdio.h </li></ul><ul><li>int putc (int ch,FILE *fp) </li></ul><ul><li>With other character function ,it is for mally called a type int,but only the lower-order byte is used. </li></ul><ul><li>To write a line of characters to a stream fputs( ) library function is used. </li></ul><ul><li>fputs( ) doesn't add a new line to the end of the string if you want u have to include it. </li></ul><ul><li>char fputs(char *str,FILE *fp); </li></ul>
  75. 75. File pointer and Fopen <ul><li>ifp = fopen(&quot;input.dat&quot;, &quot;r&quot;); </li></ul><ul><li>if(ifp == NULL) </li></ul><ul><li>{ </li></ul><ul><li>printf(&quot;can't open file &quot;); </li></ul><ul><li>exit or return </li></ul><ul><li>} </li></ul>
  76. 76. I/O with file pointer <ul><li>#include <stdio.h> </li></ul><ul><li>/* Read one line from fp, */ </li></ul><ul><li>/* copying it to line array (but no more than max chars). */ </li></ul><ul><li>/* Does not place terminating in line array. */ </li></ul><ul><li>/* Returns line length, or 0 for empty line, or EOF for end-of-file. */ </li></ul><ul><li>int fgetline(FILE *fp, char line[], int max) { </li></ul><ul><li>int nch = 0; </li></ul><ul><li>int c; </li></ul><ul><li>max = max - 1; /* leave room for '' */ </li></ul><ul><li>while((c = getc(fp)) != EOF) { </li></ul><ul><li>if(c == ' ') </li></ul><ul><li>break; </li></ul><ul><li>if(nch < max) </li></ul><ul><li>{ </li></ul><ul><li>line[nch] = c; </li></ul><ul><li>nch = nch + 1; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>if(c == EOF && nch == 0) </li></ul><ul><li>return EOF; </li></ul><ul><li>line[nch] = ''; </li></ul><ul><li>return nch; </li></ul><ul><li>} </li></ul>
  77. 77. Predefined Stream <ul><li>if((ifp = fopen(filename, &quot;r&quot;)) == NULL) </li></ul><ul><li>{ </li></ul><ul><li>fprintf(stderr, &quot;can't open file %s &quot;, filename); </li></ul><ul><li>exit or return </li></ul><ul><li>} </li></ul>
  78. 78. Closing files <ul><li>Although you can open multiple files, there's a limit to how many you can have open at once. If your program will open many files in succession, you'll want to close each one as you're done with it; otherwise the standard I/O library could run out of the resources it uses to keep track of open files. Closing a file simply involves calling fclose with the file pointer as its argument: </li></ul><ul><li>fclose(fp); </li></ul>
  79. 79. Character Input/output <ul><li>#include <stdio.h> </li></ul><ul><li>/* copy input to output */ </li></ul><ul><li>Main() { </li></ul><ul><li>int c; </li></ul><ul><li>c = getchar(); </li></ul><ul><li>while(c != EOF) </li></ul><ul><li>{ </li></ul><ul><li>putchar(c); </li></ul><ul><li>c = getchar(); </li></ul><ul><li>} </li></ul><ul><li>return 0; </li></ul><ul><li>} </li></ul>
  80. 80. UNIX File Redirection <ul><li>UNIX has a facility called redirection which allows a program to access a single input file and a single output file very easily. The program is written to read from the keyboard and write to the terminal screen as normal. </li></ul><ul><li>To run prog1 but read data from file infile instead of the keyboard, you would type </li></ul><ul><li>prog1 < infile </li></ul><ul><li>To run prog1 and write data to outfile instead of the screen, you would type </li></ul><ul><li>prog1 > outfile </li></ul><ul><li>Both can also be combined as in </li></ul><ul><li>prog1 < infile > outfile </li></ul><ul><li>Redirection is simple, and allows a single program to read or write data to or from files or the screen and keyboard. </li></ul><ul><li>Some programs need to access several files for input or output, redirection cannot do this. In such cases you will have to use C's file handling facilities. </li></ul>
  81. 81. Memory Management Dynamic memory management
  82. 82. Agenda <ul><li>Introduction / Overview </li></ul><ul><li>Memory Leak </li></ul><ul><li>Valgrind </li></ul><ul><li>Bounds Checker </li></ul><ul><li>Case study </li></ul><ul><li>Summary </li></ul><ul><li>Reference </li></ul>
  83. 83. Introduction / Overview <ul><li>Memory Allocation At Run Time Is Referred As Dynamic Memory Allocation. </li></ul><ul><li>Dynamic Memory Management Plays Is An Explicit Action In Language Like C , C++. </li></ul><ul><li>Hard Track Problems </li></ul><ul><ul><li>Freeing An Allocated Memory Twice. </li></ul></ul><ul><ul><li>Running Off The Edges Of The Alloc ‘d Buffer. </li></ul></ul><ul><ul><li>Failing To Keep Track Of Alloc ‘d Block. </li></ul></ul>
  84. 84. Memory Leak <ul><li>What is ? </li></ul><ul><ul><li>Chunk of Memory Allocated and Never been Freed in the Course of Program. </li></ul></ul><ul><ul><li>Typically happens when you reset pointer to NULL or to a New Address without freeing it first. </li></ul></ul><ul><li>How to Solve ? </li></ul><ul><ul><li>Find out where exactly Memory Leak Occurred. </li></ul></ul>
  85. 85. Memory Leak cont… <ul><li>Why is it Bad? </li></ul><ul><ul><li>Reduces the performance of the Application. </li></ul></ul><ul><ul><li>Memory Intensive and Long Run Application May Fail. </li></ul></ul><ul><ul><li>Leads to Application Crash. </li></ul></ul><ul><ul><li>Difficult to Detect. </li></ul></ul><ul><li>Are there any Tools ? </li></ul><ul><ul><li>Valgrind </li></ul></ul><ul><ul><li>Bounds Checker </li></ul></ul><ul><ul><li>Rational Purify Plus </li></ul></ul><ul><ul><li>Memprof </li></ul></ul>
  86. 86. <ul><li>Developed by Julian Seward. </li></ul><ul><li>It is Non-Intrusive. </li></ul><ul><li>Finds Memory Leak in any Application without Recompilation. </li></ul><ul><li>Identifies </li></ul><ul><ul><li>Un-initialized Data. </li></ul></ul><ul><ul><li>Reading/Writing Memory after it has been freed. </li></ul></ul><ul><ul><li>Reading/Writing Memory off the allocated Block. </li></ul></ul><ul><ul><li>Memory Leaks </li></ul></ul>Valgrind
  87. 87. <ul><li>Installation </li></ul><ul><ul><li>Where do I get Installable ? </li></ul></ul><ul><ul><ul><li>http://valgrind.kde.org/ </li></ul></ul></ul><ul><ul><li>How to Install ? </li></ul></ul><ul><ul><ul><li>From Source Package (valgrind-2.0.0.tar.bz2) </li></ul></ul></ul><ul><ul><ul><ul><li>$bunzip valgrind-2.0.0.tar.bz2 </li></ul></ul></ul></ul><ul><ul><ul><ul><li>$cd valgrind-2.0.0 </li></ul></ul></ul></ul><ul><ul><ul><ul><li>$./configure –prefix=“installation-directory” </li></ul></ul></ul></ul><ul><ul><ul><ul><li>$make </li></ul></ul></ul></ul><ul><ul><ul><ul><li>$make install </li></ul></ul></ul></ul><ul><ul><ul><li>From Binary Package (valgrind-2.0.0-1.rh90.dag.i386) </li></ul></ul></ul><ul><ul><ul><ul><li>#rpm –i –v valgrind-2.0.0-1.rh90.dag.i386 </li></ul></ul></ul></ul>Valgrind cont…
  88. 88. <ul><li>Usage </li></ul><ul><ul><li>Valgrind [val-opt] prog-to-check [prog-opt] </li></ul></ul><ul><ul><ul><li>Example </li></ul></ul></ul><ul><ul><ul><ul><li>Valgrind –skin=memcheck ls –l </li></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>`“skin” --- specifies one of the functionality valgrind supports </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>“ ls –l” --- specifies the program to be analyzed. </li></ul></ul></ul></ul></ul><ul><ul><li>Valgrind writes a commentary,detailed error reports and other significant events in user friendly format. </li></ul></ul><ul><ul><li>Output Format </li></ul></ul><ul><ul><ul><li>===process-id=== Message-from-valgrind </li></ul></ul></ul><ul><ul><ul><ul><li>example </li></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>===12343=== Invalid Read </li></ul></ul></ul></ul></ul>Valgrind cont…
  89. 89. <ul><li>Functionality Support </li></ul><ul><ul><li>Valgrind generates reports based on the value specified in the “skin” option. </li></ul></ul><ul><ul><li>The supported skin/functionalities are </li></ul></ul><ul><ul><ul><li>Memcheck </li></ul></ul></ul><ul><ul><ul><li>Addrcheck </li></ul></ul></ul><ul><ul><ul><li>Helgrind </li></ul></ul></ul><ul><ul><ul><li>Cachegrind </li></ul></ul></ul>Valgrind cont…
  90. 90. <ul><li>Memcheck </li></ul><ul><ul><li>Detects uninitialized data/memory block. </li></ul></ul><ul><ul><li>Detects Memory Leak. </li></ul></ul><ul><ul><li>Detects Invalid Memory Read/Write. </li></ul></ul><ul><ul><li>Slow compared to other functionality. </li></ul></ul><ul><li>Addrcheck </li></ul><ul><ul><li>Light Weight version of Memcheck. </li></ul></ul><ul><ul><li>Does not check for Uninitialised data/Memory. </li></ul></ul><ul><ul><li>Faster than Memcheck. </li></ul></ul>Valgrind cont…
  91. 91. <ul><li>Cachegrind </li></ul><ul><ul><li>Profiles I1,D1 and L2 Caches. </li></ul></ul><ul><ul><li>Simulates I1,D1 and L2 Caches. </li></ul></ul><ul><li>Helgrind </li></ul><ul><ul><li>Idenitifies Memory Location Which are accessed without Synchronization. </li></ul></ul><ul><ul><li>Identifies Data Race in Multithreaded Programs. </li></ul></ul>Valgrind cont…
  92. 92. <ul><li>Memcheck </li></ul><ul><ul><li>It supports 2 flags </li></ul></ul><ul><ul><ul><li>--leak-check=[no/yes] </li></ul></ul></ul><ul><ul><ul><ul><li>When disabled (no) , identifies the number of alloc ‘d and freed block. </li></ul></ul></ul></ul><ul><ul><ul><ul><li>When enabled (yes) , identifies the memory leaks. </li></ul></ul></ul></ul><ul><ul><ul><li>--show-reachable=[no/yes] </li></ul></ul></ul><ul><ul><ul><ul><li>When disabled (no) , reports block of memory for which pointer it is not available and not freed. </li></ul></ul></ul></ul><ul><ul><ul><ul><li>When enabled (yes) , reports block of memory for which pointer is available and and not freed. </li></ul></ul></ul></ul>Valgrind cont…
  93. 93. <ul><li>Uninitialised Memory (example1.c) </li></ul><ul><ul><ul><li>int main () </li></ul></ul></ul><ul><ul><ul><li>{ </li></ul></ul></ul><ul><ul><ul><li>char *cptr = NULL; </li></ul></ul></ul><ul><ul><ul><li>cptr = (char *) malloc (sizeof (char)) ; </li></ul></ul></ul><ul><ul><ul><li>if (cptr) </li></ul></ul></ul><ul><ul><ul><li>{ </li></ul></ul></ul><ul><ul><ul><li>printf (&quot;Value of cptr = [%c] &quot; ,cptr [0]) ; </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>free (cptr) ; </li></ul></ul></ul><ul><ul><ul><li>cptr = NULL ; </li></ul></ul></ul><ul><ul><ul><li>return 0 ; </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><li>$gcc –o example1 –g example1.c </li></ul></ul><ul><ul><li>$valgrind –skin=memcheck –leak-check=yes ./example1 </li></ul></ul>Case studies
  94. 94. <ul><li>Reading/Writing Freed Memory </li></ul><ul><ul><ul><li>int main () </li></ul></ul></ul><ul><ul><ul><li>{ </li></ul></ul></ul><ul><ul><ul><li>char *cptr = NULL; </li></ul></ul></ul><ul><ul><ul><li>cptr = (char *) calloc (1, sizeof (char) * 128) ; </li></ul></ul></ul><ul><ul><ul><li>if (cptr) </li></ul></ul></ul><ul><ul><ul><li>{ </li></ul></ul></ul><ul><ul><ul><li>strcpy (cptr , &quot;Example...2&quot;) ; </li></ul></ul></ul><ul><ul><ul><li>free (cptr) ; </li></ul></ul></ul><ul><ul><ul><li>printf (&quot;The Program Name is [%s] &quot; , cptr) ; </li></ul></ul></ul><ul><ul><ul><li>strcpy (cptr , &quot;End of Example 2&quot; ) ; </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>return 0 ; </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul>Case studies
  95. 95. <ul><li>Reading/Writing off the allocated block </li></ul><ul><ul><ul><li>int main () </li></ul></ul></ul><ul><ul><ul><li>{ </li></ul></ul></ul><ul><ul><ul><li>char *cptr = NULL; </li></ul></ul></ul><ul><ul><ul><li>cptr = (char *) calloc (1, sizeof (char) * 10 ) ; </li></ul></ul></ul><ul><ul><ul><li>if (cptr) </li></ul></ul></ul><ul><ul><ul><li>{ </li></ul></ul></ul><ul><ul><ul><li>strcpy (cptr , &quot;Example3&quot;) ; </li></ul></ul></ul><ul><ul><ul><li>printf (&quot;Character At position 10 is [%sc] &quot; , cptr [10]) ; </li></ul></ul></ul><ul><ul><ul><li>cptr [10] = 'c' ; </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>free (cptr) ; </li></ul></ul></ul><ul><ul><ul><li>cptr = NULL ; </li></ul></ul></ul><ul><ul><ul><li>return 0 ; </li></ul></ul></ul>Case studies
  96. 96. <ul><li>Memory Leak </li></ul><ul><ul><li>int main () </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>char *cptr = (char *) calloc (1, sizeof (char) * 25) ; </li></ul></ul><ul><ul><li>if (cptr) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>strcpy (cptr , &quot;Hello!&quot;) ; </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>function () ; </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>void function () </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>char *ptr = NULL ; </li></ul></ul><ul><ul><li>ptr = (char *) calloc (1 , sizeof (char) * 128) ; </li></ul></ul><ul><ul><li>if (ptr){ </li></ul></ul><ul><ul><li>strcpy (ptr , &quot;Example 5&quot;) ; </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>} </li></ul></ul>Case studies
  97. 97. <ul><li>Illegal Memory Free </li></ul><ul><ul><li>int main () </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>char *cptr = (char *) calloc (1, sizeof (char) * 128) ; </li></ul></ul><ul><ul><li>if (cptr) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>strcpy (cptr , &quot;Testing...&quot;) ; </li></ul></ul><ul><ul><li>printf (&quot;The string is [%s]&quot; , cptr) ; </li></ul></ul><ul><ul><li>free (cptr) ; </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>free (cptr) ; </li></ul></ul><ul><ul><li>return 0 ; </li></ul></ul><ul><ul><li>} </li></ul></ul>Case studies
  98. 98. <ul><li>Advantages </li></ul><ul><ul><li>Good memory checker and more, can also be used for profiling. </li></ul></ul><ul><ul><li>Really Fast for Memory Checker. </li></ul></ul><ul><ul><li>Code doesn’t be instrumented. </li></ul></ul><ul><ul><li>It is an open source and with excellent support </li></ul></ul><ul><li>Disadvantages </li></ul><ul><ul><li>Only available for Linux x86 </li></ul></ul><ul><ul><li>Might sometimes give false positives if code is compiled with optimization. </li></ul></ul>Valgrind cont…
  99. 99. <ul><li>Available on Window9x/2000/NT Platform. </li></ul><ul><li>Can be Used With Windows ME , If Windows ME took kit is installed. </li></ul><ul><li>Bounds Checker can be used with VC++ Integrated Environment or as a Standalone Application or from Dos Command Line. </li></ul>Bounds Checker
  100. 100. <ul><li>What it does? </li></ul><ul><ul><li>Identifies Memory Overrun. </li></ul></ul><ul><ul><li>Memory Leak. </li></ul></ul><ul><ul><li>Dangling Pointer. </li></ul></ul><ul><ul><li>Windows Function Failure. </li></ul></ul><ul><ul><li>Invalid Argument to windows Function. </li></ul></ul><ul><ul><li>Stack Memory Overrun. </li></ul></ul><ul><ul><li>Array index out of bound. </li></ul></ul><ul><ul><li>Returning Pointer to Local Variable </li></ul></ul>Bounds Checker cont…
  101. 101. <ul><li>Using Microsoft Visual C++ IDE </li></ul><ul><ul><li>On file menu , click open workspace to locate and open your program. </li></ul></ul><ul><ul><li>On bounds check menu , click integrated debugging to enable bounds checker. </li></ul></ul><ul><ul><li>On the build menu, point to start debug, and then click go. </li></ul></ul>Bounds Checker cont …
  102. 102. <ul><li>Using Bounds Check Standalone Application </li></ul><ul><ul><li>Start Bounds Checker Standalone Application </li></ul></ul><ul><ul><li>On Bounds Checker File menu, click Open. </li></ul></ul><ul><ul><li>Select the file you want to load and click open </li></ul></ul><ul><ul><li>On the program menu , click Run. </li></ul></ul>Bounds Checker cont…
  103. 103. Case studies <ul><ul><ul><li>main () </li></ul></ul></ul><ul><ul><ul><li>{ </li></ul></ul></ul><ul><ul><ul><li>char *name = NULL ; </li></ul></ul></ul><ul><ul><ul><li>int n = -1; </li></ul></ul></ul><ul><ul><ul><li>name = (char *) malloc (10) ; </li></ul></ul></ul><ul><ul><ul><li>printf (&quot;String is [%s] &quot; , name) ; </li></ul></ul></ul><ul><ul><ul><li>name [n] = 'U' ; </li></ul></ul></ul><ul><ul><ul><li>name [10] = 'O' ; </li></ul></ul></ul><ul><ul><ul><li>name = (char *) calloc (1 , sizeof (char) * 10) ; </li></ul></ul></ul><ul><ul><ul><li>free (name) ; </li></ul></ul></ul><ul><ul><ul><li>printf (&quot;The character at position 10 is [%c] &quot; , name [10]) ; </li></ul></ul></ul><ul><ul><ul><li>free (name) ; </li></ul></ul></ul><ul><ul><ul><li>return 0 ; </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul>
  104. 104. <ul><li>Array Index Outoff Range </li></ul><ul><ul><li>In C language array index starts from ‘0’. </li></ul></ul><ul><ul><li>Since n = -1 , name[n] = ‘U’ is an invalid write. </li></ul></ul><ul><ul><li>Bounds checker identifies the above error as Index Out of Range. </li></ul></ul>Case studies
  105. 105. <ul><li>Memory Overrun </li></ul><ul><ul><li>The memory block allocated for name is 10 bytes. </li></ul></ul><ul><ul><li>name [10] = ‘O’ is an invalid write. </li></ul></ul><ul><ul><li>Bounds checker identifies the above error has writing overflows memory. </li></ul></ul>Case studies
  106. 106. <ul><li>Memory Leak </li></ul><ul><ul><li>The pointer “name” pointing to previously allocated memory is reassigned with new pointer before freeing the memory block to which it was pointing. </li></ul></ul><ul><ul><li>Pointer to previously allocated memory is lost. </li></ul></ul><ul><ul><li>Bounds Checker Identifies it as memory leak. </li></ul></ul>Case studies
  107. 107. <ul><li>Dangling Pointer </li></ul><ul><ul><li>Trying to access memory which has been freed. </li></ul></ul><ul><ul><li>Bounds Checker Identifies it has Dangling Pointer. </li></ul></ul>Case studies
  108. 108. <ul><li>Dangling Pointer </li></ul><ul><ul><li>Trying to free already freed memory. </li></ul></ul><ul><ul><li>Bounds Checker Identifies the above as Dangling Pointer. </li></ul></ul>Case studies cont…
  109. 109. <ul><li>Most of the hard to trace bugs occurs in dynamic memory management. </li></ul><ul><li>Invalid free,read/writes are the most common errors. </li></ul><ul><li>Care Should be taken to avoid Array Index Out of Range </li></ul><ul><li>Memory Leak should be avoided. </li></ul><ul><li>All Variables should be initialized. </li></ul>Summary
  110. 110. <ul><li>Website </li></ul><ul><ul><li>Valgrind </li></ul></ul><ul><ul><ul><li>http://valgrind.kde.org/ </li></ul></ul></ul><ul><ul><ul><li>-Bounds Checker </li></ul></ul></ul><ul><ul><ul><li>http://www.compuware.com/products/devpartner/bounds.htm </li></ul></ul></ul>Reference
  111. 111. Linked list <ul><li>This section teaches the concepts of linked list using an example. Consider an institute that maintains records of students. </li></ul><ul><li>Data processing frequently involves storing and processing data that is organized ito a list. </li></ul><ul><li>Linked list is a self-referential data structure and consecutive collection of related data structure. </li></ul><ul><li>Each element of the list can be made to have a field, called the link or pointer,which contains the address of the next element in the list. </li></ul><ul><li>In this case successive elements need not occupy adjacent space in memory which also makes it easier to insert and delete elements in the list. </li></ul>
  112. 112. Concept of linked list <ul><li>Used to store a series of data of any type </li></ul><ul><li>Allows to manage the data effectively </li></ul><ul><li>Also known as one-way list </li></ul><ul><li>A linear collection of data elements called nodes </li></ul><ul><li>A self-referential data structure </li></ul>
  113. 113. Arrays <ul><li>An array is a collection of contiguous storage locations. Each location holds one element. All elements must be of the same type. The elements are referenced by position using an integer variable or constant called the subscript or index. In C language, the first position is position 0. </li></ul>
  114. 114. Array cont....... <ul><li>The array name represents the address of the beginning of the array. Since arrays are considered to be large structures, we do not want to waste time and space copying arrays when we pass them to subroutines. Therefore, an array is passed by reference, even if the data stored in the array won't be changed. In C-language arrays are automatically passed by reference. </li></ul>
  115. 115. Array cont....... <ul><li>In general, there are two values a user needs to be able to process an array correctly, namely, the maximum size of the array and the current size of the array. Here is a typical C-language array declaration. </li></ul>
  116. 116. Array cont....... <ul><li>#define MAX_SIZE 100 </li></ul><ul><li>int x[MAX_SIZE]; /* an array of integer */ </li></ul><ul><li>int curSize; /* how many elements are currently being used */ </li></ul><ul><li>Since numbering the elements starts at 0, the elements of array x are x[0].. x[MAX_SIZE-1]. The companion variable curSize tells us that valid data is stored at x[0]..x[curSize-1] . </li></ul>
  117. 117. Other String Handling Functions <ul><li>As well as sprintf and sscanf, the UNIX system has a number of other string handling functions within its libraries. A number of the most useful ones are contained in the <strings.h> file, and are made available by putting the line </li></ul><ul><li>#include <strings.h> </li></ul><ul><li>near to the head of your program file. </li></ul><ul><li>A couple of the functions are described below. </li></ul><ul><li>A full list of these functions can be seen using the man command by typing man 3 strings </li></ul>
  118. 118. <ul><li>When writing a large program, you may find it convenient to split it several source files. This has several advantages, but makes compilation more complicated. </li></ul><ul><li>This section will discuss advantages and disadvantages of using several files in a program, and advise you on how to divide a program between several files, should you wish to do so. </li></ul>Programs with Several Files
  119. 119. Advantage of using several files The main advantages of spreading a program across several files are: Teams of programmers can work on programs. Each programmer works on a different file. An object oriented style can be used. Each file defines a particular type of object as a datatype and operations on that object as functions. The implementation of the object can be kept private from the rest of the program. This makes for well structured programs which are easy to maintain. Files can contain all functions from a related group. For Example all matrix operations. These can then be accessed like a function library. Well implemented objects or function definitions can be re-used in other programs, reducing development time. In very large programs each major function can occupy a file to itself. Any lower level functions used to implement them can be kept in the same file. Then programmers who call the major function need not be distracted by all the lower level work. When changes are made to a file, only that file need be re-compiled to rebuild the program. The UNIX make facility is very useful for rebuilding multi-file programs in this way.
  120. 120. How to Divide a Program between Several Files Where a function is spread over several files, each file will contain one or more functions. One file will include main while the others will contain functions which are called by others. These other files can be treated as a library of functions. Programmers usually start designing a program by dividing the problem into easily managed sections. Each of these sections might be implemented as one or more functions. All functions from each section will usually live in a single file. Where objects are implemented as data structures, it is usual to to keep all functions which access that object in the same file. The advantages of this are; The object can easily be re-used in other programs.
  121. 121. How to Divide a Program between Several Files All related functions are stored together. Later changes to the object require only one file to be modified. Where the file contains the definition of an object, or functions which return values, there is a further restriction on calling these functions from another file. Unless functions in another file are told about the object or function definitions, they will be unable to compile them correctly. The best solution to this problem is to write a header file for each of the C files. This will have the same name as the C file, but ending in .h. The header file contains definitions of all the functions used in the C file. Whenever a function in another file calls a function from our C file, it can define the function by making a #include of the appropriate .h file.
  122. 122. Organization of Data in File Any file must have its data organized in a certain order. This will typically be: A preamble consisting of #defined constants, #included header files and typedefs of important data types Declaration of global and external variables. Global variables may also be initialized here. One or more functions. The order of items is important, since every object must be defined before it can be used. Functions which return values must be defined before they are called. This definition might be one of the following:
  123. 123. Organization of Data in File Where the function is defined and called in the same file, a full declaration of the function can be placed ahead of any call to the function. If the function is called from a file where it is not defined, a prototype should appear before the call to the function. A function defined as float find_max(float a, float b, float c) { /* etc ... ... */ would have a prototype of float find_max(float a, float b, float c); The prototype may occur among the global variables at the start of the source file. Alternatively it may be declared in a header file which is read in using a #include. It is important to remember that all C objects should be declared before use.
  124. 124. <ul><li>This process is rather more involved than compiling a single file program. Imagine a program in three files prog.c, containing main(), func1.c and func2.c. The simplest method of compilation (to produce a runnable file called a.out) </li></ul><ul><li>cc prog.c func1.c func2.c </li></ul><ul><li>If we wanted to call the runnable file prog we would have to type </li></ul><ul><li>cc prog.c func1.c func2.c -o prog </li></ul><ul><li>In these examples, each of the .c files is compiled, and then they are automatically linked together using a program called the loader ld. </li></ul>Compiling Multi-File Programs
  125. 125. <ul><li>We can also compile each C file separately using the cc -c option. This produces an object file with the same name, but ending in .o. After this, the object files are linked using the linker. This would require the four following commands for our current example. </li></ul><ul><li>cc -c prog.c </li></ul><ul><li>cc -c func1.c </li></ul><ul><li>cc -c func2.c </li></ul><ul><li>ld prog.o func1.o func2.o -o prog </li></ul><ul><li>Each file is compiled before the object files are linked to give a runnable file. </li></ul><ul><li>The advantage of separate compilation is that only files which have been edited since the last compilation need to be re-compiled when re-building the program. For very large programs this can save a lot of time. </li></ul><ul><li>The make utility is designed to automate this re-building process. It checks the times of modification of files, and selectively re-compiles as required. It is an excellent tool for maintaining multi-file programs. Its use is recommended when building multi-file programs </li></ul>Separate Compilation
  126. 126. <ul><li>We have already used make to build single file programs. It was really designed to help build large multi-file programs. Its use will be described here. </li></ul><ul><li>Make knows about `dependencies' in program building. For example; </li></ul><ul><li>* We can get prog.o by running cc -c prog.c. </li></ul><ul><li>* This need only be done if prog.c changed more recently than prog.o. </li></ul><ul><li>make is usually used with a configuration file called Makefile which describes the structure of the program. This includes the name of the runnable file, and the object files to be linked to create it. Here is a sample Makefile for our current example </li></ul><ul><li># Sample Makefile for prog </li></ul><ul><li># </li></ul><ul><li># prog is built from prog.c func1.c func2.c </li></ul>Using make with Multi-File Programs
  127. 127. <ul><li># Object files (Ending in .o, </li></ul><ul><li># these are compiled from .c files by make) </li></ul><ul><li>OBJS = prog.o func1.o func2.o </li></ul><ul><li># Prog is generated from the object files </li></ul><ul><li>prog: $(OBJS) </li></ul><ul><li>$(CC) $(CFLAGS) -o prog $(OBJS) </li></ul><ul><li># ^^^ This space must be a TAB. </li></ul><ul><li># Above line is an instruction to link object files </li></ul><ul><li>This looks cluttered, but ignore the comments (lines starting with #) andthere are just 3 lines. </li></ul><ul><li>When make is run, Makefile is searched for a list of dependencies. The compiler is involved to create .o files where needed. The link statement is then used to create the runnable file. </li></ul><ul><li>make re-builds the whole program with a minimum of re-compilation, and ensures that all parts of the program are up to date. It has many other features, some of which are very complicated. </li></ul><ul><li>For a full description of all of these features, look at the manual page for make by typing </li></ul>Using make with Multi-File Programs CONT....
  128. 128. Reading lines <ul><li>while((c = getchar()) != EOF && c != ' ') </li></ul><ul><li>{ </li></ul><ul><li>if(nch < max) </li></ul><ul><li>{ </li></ul><ul><li>line[nch] = c; </li></ul><ul><li>nch = nch + 1; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  129. 129. Reading number <ul><li>#include <stdlib.h> </li></ul><ul><li>char line[256]; </li></ul><ul><li>double x; </li></ul><ul><li>printf(&quot;Type a floating-point number: &quot;); </li></ul><ul><li>getline(line, 256); </li></ul><ul><li>x = atof(line); </li></ul>
  130. 130. IntelliBitz Technologies Training Division 168, Medavakkam Main Road Madipakkam, Chennai 91. PH: +91 044 2247 5106 www.intellibitz.com [email_address]