cprogrammingtutorial

Download CProgrammingTutorial

If you can't read please download the document

Upload: muthuselvam-rs

Post on 16-Apr-2017

6.240 views

Category:

Technology


0 download

TRANSCRIPT

INTELLIBITZ TechnologiesPHP Web ProgrammingTD_PHP_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0

C Programming

A computer needs to be programmed to solve a problem.

C is a programming language developed at AT&T bell labs.

Any programming Language can be divided in to two categories.

Problem oriented (High level language)

Machine oriented (low level language)

C is considered as a middle level Language.

C is modular,portable,reusable

C is a language of few words that are known as keyword.

C code can be written in routines called function

Algorithm: to understand about the program

C is famous because reliable,simple,easy

Compactness,generality,efficiency,modularity and simplicity

Preparing to program

(1)Determine the objective of the program.

Determine the methods you want to use .

Create the program to solve the problem

Run the program for output

Feature of C Program

Structured language

General purpose language

Portability

Code Re usability

Ability to customize and extend

Limited Number of Key Word


Structured Language

It has the ability to divide and hide all the information and instruction.

Code can be partitioned in C using functions or code block.

C is a well structured language compare to other.

Portability

Portability is the ability to port or use the software written .

One computer C program can be reused.

By modification or no modification.

General Purpose Language

Make it ideal language for system programming.

It can also be used for business and scientific application.

ANSI established a standard for c in 1983.

The ability of c is to manipulate bits,byte and addresses.

It is adopted in later 1990.

Code Re usability and Ability to
Customize and Extend

A programmer can easily create his own function

It can can be used repeatedly in different application

C program basically collection of function

The function are supported by 'c' library

Function can be added to 'c' library continuously


Limited number of keywords
and unix library function

There are only 32 keywords in 'C'

27 keywords are given by ritchie

5 is added by ANSI

the strength of 'C' is lies in its in-built function

unix system provides as large number of C function

some function are used in operation .

other are for specialized in their application

'C' program structure

Pre-processor directives

Global declarations

Main( )

{

Local variable deceleration

Statement sequences

Function invoking

}

Writing,compiling and executing

Program need to be compiled before execution

'C' is case sensitive

Linking is the process of joining other program files

All keywords are lowercased

C is case sensitive

Keywords cannot be used for any other purpose

C statement always ends with a semicolon

No blank spaces are allowed with in a variable,constant or keyword

File should be have the extension .c

Recap of previous session

Introduction to programming

Features of 'C'

Writing,Compiling,Linking and executing

Writing a 'C' program

Introduction

Data types are used to declare a variety of different values.

Variables are important tool of a programmer

They are used to keep account of various values .

Like in a game ,weight or height of the player etc

Data types

Variable is an identifier

Variable must be declared before it is used in the program

'C' has 5 basic built-in data types

'C' supports aggregates data types

Data type defines a set of values that a variable can store along with a set of operations that can be performed on it.

A variable takes different values at different times

Modifiers are used to alter the meaning of the base type to fit the needs of various situations more precisely .

'C' has five basic built in data type

Char (character value)

Int (integer value)

Float (Floating point value)

Double (Double floating point value)

Void (Valueless)

Void is used to

Declare explicitly that a function is not returning a value

Declare explicitly that a function has no parameter

Create generic pointer

'C' also supports several aggregate types including structure ,union ,enumeration and user defined types.


Declaring a variable

A variable should be declare before it is used in the program

Example: data-type var-list;

Data type must be valid data type and var-list may be consist of one or more identifier names separated by commas operator.

The declaration indicates the compiler about the variable names and types of data

Example : int count;

double balance;

float amount;

Int, double,and float are keywords and cannot be used as variable names.

Assigning values

Values can be assigned to variable using the assignment operator (=).

var-name=expression;

An expression can be a single constant or combination of variables,operators and constants.

Data-type var-name=constant;

int value=250;

char name= salini

double amount =76.80

Type Modifier

The basic data types may have various modifiers preceding them except type void.

A modifier is used to alter the meaning of the base type to fit the needs of various situations more precisely.

The list of modifier:

Signed

Unsigned

Long

Short

Character

This is a group of 8 data bits.

'C' represents either a letter of roman alphabet.

Small integer in the range of 0 through to +255.

To give a named memory area in which a single letter has to be stored

Declaration

char letter;

Integer

There are two types of integers

Short

Long

The actual number of bits used in these types is implementation dependent.

For sixteen bit machine ,the long integer is two machine words long,and short integer is one machine word long.

short int smaller_number;

long int big_number;

Real number

Float offers two sizes-float and double that are similar to integer type

Approximately float represents six significant digit and double is twelve.

float length_of_water_line;

double displacement;

Signed and unsigned prefixes

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.

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.

The default for the int types is always signed,and char is machine dependent.

Character Set

Characters are used to form the words, numbers and expression

The characters in 'C' are grouped into the following categories:

character set- alphabets from A....Z,a....z

All decimal digits from 0.....9

Special characters include

, . ; : ? ' " ! / \ | ~ - $

% # & ^ * _ + < > ( ) { } [ ] blank space

Keywords and Indentifier

Every ' C' word is classified as either a keyword or an identifier.

All identifier have fixed meaning, which can not be changed.

Rules for identifier

Legal characters are a-z, A-Z,0-9 and _

Case significant

The first character must be a letter or _

Identifier can be of any length

The reserved keywords should not be used as identifier.

Valid identifier invalid identifier

Count . 1count

Test23 .hi!

high_bal . high balance

keywords

Auto double int struct break

Long switch case enum register

Typedef char extern return union

Float unsigned short continue for

Signed void default goto sizeof

Volatile do if static while

Else const

Constants

Supports numerical as well as character constants.

'C' supports several types of constants.

'C' has two types of modifier.

Variable of type const cannot be modified

Constants are fixed values that do not change during the execution of a program.

'C' supports both numeric and character constants

C supports several types constant

Numeric constant

Integer constant

Floating point (real) constant

Character constant

Single character constant

String constant

The following rules apply to all numeric constant

Non- digit characters and blanks cannot be included

Can be preceded by minus sign

Escape sequences

Certain non printing characters as well as the backslash (\) and the apostrophe('), can be expressed in terms of escape sequence.

Example for new line \n

Bell \a carriage return \r

Backspace \b formfeed \f

Horizontal tab \t quotation mark \

Vertical tab \v apostrophe \'

Backslash \\ question mark \?

Null \0

Access modifier

C has two type modifiers that can be used to control the way in which variables may be accessed or modified.

These are

Const

example const int my_age=39;

Volatile

example volatile int date

Operator

Three kinds of operators.

Two types of casting.

'C' includes a class of operators .

That act upon a single operand to produce a new value.

Ternary operator operates on three operands.

'C' is very rich in built -in operator.

An operator is a symbol that indicates the compiler to perform specific mathematical or logical manipulation.



Three general classes of operator

Arithmetic operator

Relational operator

Assignment operator

Special operators to perform particular task

Ternary (conditional) operator

Size of operator

Comma operator

& Operator

. and -> operator

Arithmetic Operators

Operator Action Example

_ Subtraction a-b

+ Addition a+b

* Multiplication a*b

/ division a/b

% modulus Division a%b

- Decrement a- or -a

++ increment a+ or ++

casting

When operand differ in type they may undergo type conversion before the expression takes on its final value.

The final result will be expressed in the highest precision possible, consistent with data type of the operand.

There are two types of casting

Implicit

Explicit

Implicit casting

If either operand is long double, convert the other to long double

If either operand is double , convert the other to float.

Convert char and short to int.

If either operand is long convert the other to long.

Explicit casting

The expression can be converted to a different data type if desired data type, enclosed in parentheses

(data type) expression

int a+m;

sqrt ((double)x)

The cast produces the value of the proper type;x itself is not altered

Linking with math library

This is following code links to the math library

cc -o cast cast.c lm

the -l switch stands for 'library'

The library that is searched in the case is libm.a the path u search that is '/usr/lib' where libm.a is found.

Unary operator

'C' include a class of operators that act upon a single operand to produce a new value.

The most common unary operation is unary minus.

Example

-143 -(a+m)

-12 -3.2

Increment and Decrement

x=x+1;

x+=1;

x++;

x=x-1;

x-=1;

Postfix and Prefix

A postfix expression is obtained by post fixing a++ or operator

The value of the expression is the value of the operand.

x=10;

y=++x;

x=10;

y=x++;

Relational and Logical operator

Operator Meaning

< is less then

is greater then

>= is greater then or equal to

== is equal to

!= is not equal

&& Logical AND

|| Logical OR

! Logical NOT

Conditional (:?) Operator

var=exp1?exp2:exp3

x=10;

y=x>9 ?100:200;

x=10;

if (x>9)

{

y=100;

}

else

{

y=200;

}

Recap of previous session

Data type

Constants

Operator

POINTERS

Simply stated, a pointer is an address. Instead of being a variable, it is a pointer to a variable stored

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.

For the moment, ignore the data definition statement where we define index and two other fields

POINTERS CONT..

beginning with a star. It is properly called an asterisk, but for reasons we will see later, let's agree to call

it a star. If you observe the statement in line 8, it should be clear that we assign the value of 39 to the

variable named index. This is no surprise, we have been doing it for several programs now. The

statement in line 9 however, says to assign to pt1 a strange looking value, namely the variable index with

POINTERS CONT....

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

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.

The following two rules will be somewhat confusing to you at first, but we need to state the definitions

before we can use them. Take your time, and the whole thing will clear up very quickly.

POINTERS

TWO VERY IMPORTANT RULES

The following two rules are very important when using pointers and must be thoroughly understood.

1. A variable name with an ampersand in front of it defines the address of the variable and therefore points to the variable. .

2. A pointer with a star in front of it refers to the value of the variable pointed to by the pointer line.

POINTERS

Twelve of the program can be read as "The stored (starred) value to which the pointer pt1 points is

assigned the value 13". 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.

MEMORY AIDS

1. Think of & as an address.

2. Think of * as a star referring to stored.

NULL POINTERS

#include

int *ip = NULL;

if(ip != NULL)

printf("%d\n", *ip);

NULL POINTERS

#include

char *mystrstr(char input[], char pat[]) {

char *start, *p1, *p2;

for(start = &input[0]; *start != '\0'; start++)

{/* for each position in input string... */

p1 = pat;/* prepare to check for pattern string there */

p2 = start;

while(*p1 != '\0'){

if(*p1 != *p2)/* characters differ */

break;

p1++;

p2++;

}

if(*p1 == '\0')/* found match */

return start;

}

return NULL;

}

Equivalence in Array and pointer

There are a number of similarities between arrays and pointers in C. If you have an array

int a[10];

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:

int *ip = &a[0];

Arrays and Pointers as Function Arguments

int getline(char *line, int max){

int nch = 0;

int c;

max = max - 1;/* leave room for '\0' */

#ifndef FGETLINE

while((c = getchar()) != EOF)

#else

while((c = getc(fp)) != EOF)

#endif{

if(c == '\n')

break;

if(nch < max){

line[nch] = c;

nch = nch + 1;

}

}

if(c == EOF && nch == 0)

return EOF;

line[nch] = '\0';

return nch;

}

String

char internal_string_1[] = "Hello";

char internal_string_2[] = "world";

char *p1 = &internal_string_1[0];

int len = strlen(&internal_string_2[0]);

Preprocessor Directives

Preprocessor directives are instructions to the compiler that begin with a # sign.

Executed before the compilation begin.

Most frequently used directives

- #include

- #define

Notes

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

A header or a standard library contain a set of related functions,which perform various tasks in a program.

Header file generally have extension '.h'.

stdio.h contains a set of console i/o functions

#include referred to as nested includes.

The number of nesting varies from compiler to compiler.

Header files are usually placed in a special library called include .

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.

Macros

Macro is imperative that there is no space between the macro name and the opening parenthesis.

#include stdio.h #define START 0 /*starting point of loop*/

#define ENDING 9 /*Ending point of loop*/

#define MAX (A,B) ((A)>(B)?(B):(A)) /*Max macro definition*/

#define MIN (A,B) ((A)>(B)?(B):(A)) /*Min macro definition*/

main ( )

{

int index, mn,mx;

int count = 5

.

mx=max (index,count);

mn=min(index,count);

.

.

}

Getchar( )

The simplest i/o function to read the input and show the standard output .

The getchar( ) function reads a single character from the console.

The function does not require any arguments,through a pair of parentheses must follow the word getchar.

Example

=getchar( );

char name;

name =getchar( );

Putchar( )

Single character can be written to the terminal using the 'C' library function putchar( ) Example

putchar (var_name)

name ='A'

putchar(name)

The above putchar ( ) will display the character A on the screen

Printf( )

The printf( )function provides certain features that can be effectively exploited to control the alignment and spacing of prints outs on the terminal.

printf(format-string,arg1,arg2,arg3,......);

The format -strings defines the way in which the subsequent argument arg1,arg2...are to be displayed.

The format string consist of two types

-Character that will be printed on the terminal.

-format commands that defines the output format of each argument

Printf(hello %c %d %s, 'x', '12', there!);

will display

hello x 12 there!

Scanf( )

Scanf is used for reading in data from the standard input (keyboard).

Scanf (format-string &arg1,&arg2...);

The format string may include:

Field specifier

Optional field width

Optional white and non-whit character.

Example:

scanf (%d, &count);

List all format

Code Format

%c Character

%d Signed decimal integer

%i Signed decimal integer

%e Scientific notation[e]

%E Scientific notation[E]

%f Decimal floating point

%o unsigned octal

%s String of character

%u unsigned decimal integer

%x unsigned Hexadecimal (lower)

%X unsigned Hexadecimal (upper)

%p dispaly a pointer

%% print a %

Mixed data Output

It is permitted to mix data types in one printf statement.

Example

Printf (%d%f%s%c, a,b,c,d);

this is big advantage in the 'C' .

Types

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.

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.

Types

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.

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.

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.

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.

Types cont...

There are only a few basic data types in C. The first ones we'll be encountering and using are:

* char a character

* int an integer, in the range -32,767 to 32,767

* long int a larger integer (up to +-2,147,483,647)

* float a floating-point number

* double a floating-point number, with more precision and perhaps greater range than float

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.)

Declaration

.You may wonder why variables must be declared before use. There are two reasons:

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.

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.)

Function calls

printf("Hello, world!\n")

printf("%d\n", i)

sqrt(144.)

Getchar()

Expression statement

Most of the statements in a C program are expression statements. An expression statement is simply an expression followed by a semicolon. The lines

i = 0;

i = i + 1;

and

printf("Hello, world!\n");

If statement

if( expression )

{

statement1

statement2

statement3

}

Boolean expression

=greater than or equal

==equal

!=not equal

While loop

int x = 2;

while(x < 1000)

{

printf("%d\n", x);

x = x * 2;

}

For loop

for (i = 0; i < 10; i = i + 1)

printf("i is %d\n", i);

Break and continue

#include

#include

Main() {

int i, j;

printf("%d\n", 2);

for(i = 3; i sqrt(i))

{

printf("%d\n", i);

break;

}

}

}

return 0;

}

Character output

The library function putc ( ) writes a single character to a specified stream. Its prototype, in stdio.h

int putc (int ch,FILE *fp)

With other character function ,it is for mally called a type int,but only the lower-order byte is used.

To write a line of characters to a stream fputs( ) library function is used.

fputs( ) doesn't add a new line to the end of the string if you want u have to include it.

char fputs(char *str,FILE *fp);

File pointer and Fopen

ifp = fopen("input.dat", "r");

if(ifp == NULL)

{

printf("can't open file\n");

exit or return

}

I/O with file pointer

#include

/* Read one line from fp, */

/* copying it to line array (but no more than max chars). */

/* Does not place terminating \n in line array. */

/* Returns line length, or 0 for empty line, or EOF for end-of-file. */

int fgetline(FILE *fp, char line[], int max) {

int nch = 0;

int c;

max = max - 1;/* leave room for '\0' */

while((c = getc(fp)) != EOF) {

if(c == '\n')

break;

if(nch < max)

{

line[nch] = c;

nch = nch + 1;

}

}

if(c == EOF && nch == 0)

return EOF;

line[nch] = '\0';

return nch;

}

Predefined Stream

if((ifp = fopen(filename, "r")) == NULL)

{

fprintf(stderr, "can't open file %s\n", filename);

exit or return

}

Closing files

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:

fclose(fp);

Character Input/output

#include

/* copy input to output */

Main() {

int c;

c = getchar();

while(c != EOF)

{

putchar(c);

c = getchar();

}

return 0;

}

UNIX File Redirection

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.

To run prog1 but read data from file infile instead of the keyboard, you would type

prog1 < infile

To run prog1 and write data to outfile instead of the screen, you would type

prog1 > outfile

Both can also be combined as in

prog1 < infile > outfile

Redirection is simple, and allows a single program to read or write data to or from files or the screen and keyboard.

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.

Memory Management

Dynamic memory management

Agenda

Introduction / Overview

Memory Leak

Valgrind

Bounds Checker

Case study

Summary

Reference

Introduction / Overview

Memory Allocation At Run Time Is Referred As Dynamic Memory Allocation.

Dynamic Memory Management Plays Is An Explicit Action In Language Like C , C++.

Hard Track Problems

Freeing An Allocated Memory Twice.

Running Off The Edges Of The Alloc d Buffer.

Failing To Keep Track Of Alloc d Block.

Memory Leak

What is ?

Chunk of Memory Allocated and Never been Freed in the Course of Program.

Typically happens when you reset pointer to NULL or to a New Address without freeing it first.

How to Solve ?

Find out where exactly Memory Leak Occurred.

Memory Leak cont

Why is it Bad?

Reduces the performance of the Application.

Memory Intensive and Long Run Application May Fail.

Leads to Application Crash.

Difficult to Detect.

Are there any Tools ?

Valgrind

Bounds Checker

Rational Purify Plus

Memprof

Developed by Julian Seward.

It is Non-Intrusive.

Finds Memory Leak in any Application without Recompilation.

Identifies

Un-initialized Data.

Reading/Writing Memory after it has been freed.

Reading/Writing Memory off the allocated Block.

Memory Leaks

Valgrind

Installation

Where do I get Installable ?

http://valgrind.kde.org/

How to Install ?

From Source Package (valgrind-2.0.0.tar.bz2)

$bunzip valgrind-2.0.0.tar.bz2

$cd valgrind-2.0.0

$./configure prefix=installation-directory

$make

$make install

From Binary Package (valgrind-2.0.0-1.rh90.dag.i386)

#rpm i v valgrind-2.0.0-1.rh90.dag.i386

Valgrind cont

Usage

Valgrind [val-opt] prog-to-check [prog-opt]

Example

Valgrind skin=memcheck ls l

`skin --- specifies one of the functionality valgrind supports

ls l --- specifies the program to be analyzed.

Valgrind writes a commentary,detailed error reports and other significant events in user friendly format.

Output Format

===process-id=== Message-from-valgrind

example

===12343=== Invalid Read

Valgrind cont

Functionality Support

Valgrind generates reports based on the value specified in the skin option.

The supported skin/functionalities are

Memcheck

Addrcheck

Helgrind

Cachegrind

Valgrind cont

Memcheck

Detects uninitialized data/memory block.

Detects Memory Leak.

Detects Invalid Memory Read/Write.

Slow compared to other functionality.

Addrcheck

Light Weight version of Memcheck.

Does not check for Uninitialised data/Memory.

Faster than Memcheck.

Valgrind cont

Cachegrind

Profiles I1,D1 and L2 Caches.

Simulates I1,D1 and L2 Caches.

Helgrind

Idenitifies Memory Location Which are accessed without Synchronization.

Identifies Data Race in Multithreaded Programs.

Valgrind cont

Memcheck

It supports 2 flags

--leak-check=[no/yes]

When disabled (no) , identifies the number of alloc d and freed block.

When enabled (yes) , identifies the memory leaks.

--show-reachable=[no/yes]

When disabled (no) , reports block of memory for which pointer it is not available and not freed.

When enabled (yes) , reports block of memory for which pointer is available and and not freed.

Valgrind cont

Uninitialised Memory (example1.c)

int main ()

{

char *cptr = NULL;

cptr = (char *) malloc (sizeof (char)) ;

if (cptr)

{

printf ("Value of cptr = [%c]\n" ,cptr [0]) ;

}

free (cptr) ;

cptr = NULL ;

return 0 ;

}

$gcc o example1 g example1.c

$valgrind skin=memcheck leak-check=yes ./example1

Case studies

Reading/Writing Freed Memory

int main ()

{

char *cptr = NULL;

cptr = (char *) calloc (1, sizeof (char) * 128) ;

if (cptr)

{

strcpy (cptr , "Example...2") ;

free (cptr) ;

printf ("The Program Name is [%s]\n" , cptr) ;

strcpy (cptr , "End of Example 2" ) ;

}

return 0 ;

}

Case studies

Reading/Writing off the allocated block

int main ()

{

char *cptr = NULL;

cptr = (char *) calloc (1, sizeof (char) * 10 ) ;

if (cptr)

{

strcpy (cptr , "Example3") ;

printf ("Character At position 10 is [%sc]\n" , cptr [10]) ;

cptr [10] = 'c' ;

}

free (cptr) ;

cptr = NULL ;

return 0 ;

Case studies

Memory Leak

int main ()

{

char *cptr = (char *) calloc (1, sizeof (char) * 25) ;

if (cptr)

{

strcpy (cptr , "Hello!") ;

}

function () ;

}

void function ()

{

char *ptr = NULL ;

ptr = (char *) calloc (1 , sizeof (char) * 128) ;

if (ptr){

strcpy (ptr , "Example 5") ;

}

}

Case studies

Illegal Memory Free

int main ()

{

char *cptr = (char *) calloc (1, sizeof (char) * 128) ;

if (cptr)

{

strcpy (cptr , "Testing...") ;

printf ("The string is [%s]" , cptr) ;

free (cptr) ;

}

free (cptr) ;

return 0 ;

}

Case studies

Advantages

Good memory checker and more, can also be used for profiling.

Really Fast for Memory Checker.

Code doesnt be instrumented.

It is an open source and with excellent support

Disadvantages

Only available for Linux x86

Might sometimes give false positives if code is compiled with optimization.

Valgrind cont

Available on Window9x/2000/NT Platform.

Can be Used With Windows ME , If Windows ME took kit is installed.

Bounds Checker can be used with VC++ Integrated Environment or as a Standalone Application or from Dos Command Line.

Bounds Checker

What it does?

Identifies Memory Overrun.

Memory Leak.

Dangling Pointer.

Windows Function Failure.

Invalid Argument to windows Function.

Stack Memory Overrun.

Array index out of bound.

Returning Pointer to Local Variable

Bounds Checker cont

Using Microsoft Visual C++ IDE

On file menu , click open workspace to locate and open your program.

On bounds check menu , click integrated debugging to enable bounds checker.

On the build menu, point to start debug, and then click go.

Bounds Checker cont

Using Bounds Check Standalone Application

Start Bounds Checker Standalone Application

On Bounds Checker File menu, click Open.

Select the file you want to load and click open

On the program menu , click Run.

Bounds Checker cont

Case studies

main ()

{

char *name = NULL ;

int n = -1;

name = (char *) malloc (10) ;

printf ("String is [%s]\n" , name) ;

name [n] = 'U' ;

name [10] = 'O' ;

name = (char *) calloc (1 , sizeof (char) * 10) ;

free (name) ;

printf ("The character at position 10 is [%c]\n" , name [10]) ;

free (name) ;

return 0 ;

}

Array Index Outoff Range

In C language array index starts from 0.

Since n = -1 , name[n] = U is an invalid write.

Bounds checker identifies the above error as Index Out of Range.

Case studies

Memory Overrun

The memory block allocated for name is 10 bytes.

name [10] = O is an invalid write.

Bounds checker identifies the above error has writing overflows memory.

Case studies

Memory Leak

The pointer name pointing to previously allocated memory is reassigned with new pointer before freeing the memory block to which it was pointing.

Pointer to previously allocated memory is lost.

Bounds Checker Identifies it as memory leak.

Case studies

Dangling Pointer

Trying to access memory which has been freed.

Bounds Checker Identifies it has Dangling Pointer.

Case studies

Dangling Pointer

Trying to free already freed memory.

Bounds Checker Identifies the above as Dangling Pointer.

Case studies cont

Most of the hard to trace bugs occurs in dynamic memory management.

Invalid free,read/writes are the most common errors.

Care Should be taken to avoid Array Index Out of Range

Memory Leak should be avoided.

All Variables should be initialized.

Summary

Website

Valgrind

http://valgrind.kde.org/

-Bounds Checker

http://www.compuware.com/products/devpartner/bounds.htm

Reference

Linked list

This section teaches the concepts of linked list using an example. Consider an institute that maintains records of students.

Data processing frequently involves storing and processing data that is organized ito a list.

Linked list is a self-referential data structure and consecutive collection of related data structure.

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.

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.

Concept of linked list

Used to store a series of data of any type

Allows to manage the data effectively

Also known as one-way list

A linear collection of data elements called nodes

A self-referential data structure

Arrays

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.

Array cont.......

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.

Array cont.......

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.

Array cont.......

#define MAX_SIZE 100

int x[MAX_SIZE]; /* an array of integer */

int curSize; /* how many elements are currently being used */

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].

Other String Handling Functions

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 file, and are made available by putting the line

#include

near to the head of your program file.

A couple of the functions are described below.

A full list of these functions can be seen using the man command by typing man 3 strings


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.

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.

Programs with Several Files


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.


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.


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.


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:


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.


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)

cc prog.c func1.c func2.c

If we wanted to call the runnable file prog we would have to type

cc prog.c func1.c func2.c -o prog

In these examples, each of the .c files is compiled, and then they are automatically linked together using a program called the loader ld.

Compiling Multi-File Programs


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.

cc -c prog.c

cc -c func1.c

cc -c func2.c

ld prog.o func1.o func2.o -o prog

Each file is compiled before the object files are linked to give a runnable file.

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.

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

Separate Compilation


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.

Make knows about `dependencies' in program building. For example;

* We can get prog.o by running cc -c prog.c.

* This need only be done if prog.c changed more recently than prog.o.

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

# Sample Makefile for prog

#

# prog is built from prog.c func1.c func2.c

Using make with Multi-File Programs


# Object files (Ending in .o,

# these are compiled from .c files by make)

OBJS = prog.o func1.o func2.o

# Prog is generated from the object files

prog: $(OBJS)

$(CC) $(CFLAGS) -o prog $(OBJS)

# ^^^ This space must be a TAB.

# Above line is an instruction to link object files

This looks cluttered, but ignore the comments (lines starting with #) andthere are just 3 lines.

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.

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.

For a full description of all of these features, look at the manual page for make by typing

Using make with Multi-File Programs CONT....

Reading lines

while((c = getchar()) != EOF && c != '\n')

{

if(nch < max)

{

line[nch] = c;

nch = nch + 1;

}

}

Reading number

#include

char line[256];

double x;

printf("Type a floating-point number:\n");

getline(line, 256);

x = atof(line);

IntelliBitz Technologies
Training Division
168, Medavakkam Main Road
Madipakkam, Chennai 91.
PH: +91 044 2247 5106
www.intellibitz.com
[email protected]

INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0

www.intellibitz.com [email protected]

Click to edit the title text format

www.intellibitz.com [email protected]

INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)Dynamic memory managementINTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0INTELLIBITZ TechnologiesSystem Engineer (C)SE_CCC_V1.0.0