Fundamentals of Computer and Programming in C: (CSE - 101 F)
Fundamentals of Computer and Programming in C: (CSE - 101 F)
Fundamentals of Computer and Programming in C: (CSE - 101 F)
Programming in C
(CSE -101 F)
Prepared By:
Ms.Aanchal Aggarwal
[email protected]
A.P in CSE department
CSE/IT
1/338
Syllabus
CSE-101-F
Section A
An Overview of Computer System and Operating Systems:
Fundamentals :- Evaluation of computers, Hardware organization of a computer, Introduction to
microprocessor, generations of microprocessors, Commonly used CPUs, Input/Output devices,
Input/Output ports and connectors.
Operating System Basics: Introduction to Operating system, Functions of an Operating Systems,
Classification of Operating Systems, Basic introduction to DOS, UNIX/LINUX OS, Windows XP.
Section B
Basic Introduction to System Software and Programs:Machine Language, Assembly Languages, Low level languages, High level Languages, Types of high level
languages, Compiler, Interpreter, Assembler, Loader, Linker, Relationship between Compiler, Interpreter,
Loader and Linker.
Basic Introduction to Computer Networks :Data Communication, modulation, Network devices, LAN, LAN topologies, WAN, OSI Reference model,
Introduction to Internet and protocols : TCP/IP Reference model, Backbone network, Network connecting
devices, Hypertext documents, HTTP, DNS, Network Security.
CSE/IT
2/338
Syllabus
Section C
An Overview of C:
Constants, Variables and Data types, operators and Expressions, managing I/O operations, Decision Making and
branching, Decision Making and looping, Arrays, Character Arrays and Strings, User Defined Functions.
Structure and Union in C :
Defining structure, declaring variables, Accessing structure members, structure initialization, copying and
comparing structures variables, operations on individual members, Array of structure, structure with
structure,unions, size of structure.
Section D
Pointers in C :
Introduction, Understanding Pointers, Accessing the address of a variable, Declaring Pointer Variables,
Initialization of Pointer Variables, Accessing a variable through its pointer, Chain of Pointers, Pointer
Expressions, Pointer Increments and Scale Factors, pointers and Arrays, Pointer and Character Strings,
Arrays of Pointers, Pointers as Function Arguments, Functions Returning Pointers, Pointers to Functions.
Dynamic Memory Allocation and File Management in C :Introduction, Dynamic memory allocation, allocating a block of memory: Malloc, allocating multiple blocks of
memory: Calloc. Releasing the used space: Free, Altering the size of block: Realloc, Defining and opening file,
closing file, I/O operation on files, error handling during I/O operations, Random Access to files and
command line arguments.
CSE/IT
3/338
Assessment Criteria
Total : 150 Marks
Theory Exam : 100 Marks
Marks of Class Work:50
Sessional
:15 Marks
Pre-University
:15 Marks
Attendance
:10 Marks
Class Performance :10 Marks
CSE/IT
4/338
Background
Basics of computer
Knowledge of operating systems
Knowledge of programming languages
Knowledge of compilers and interpreters
CSE/IT
5/338
References
Fundamental of Computers and Programing with
C, by A. K. Sharma, Dhanpat Rai Publications, New
Delhi.
Fundamental of Information Technology, by
A.Leon & M.Leon.
Computer Networks ,4th Edition, by Andrew S.
Tanenbaum
Programming in C, by Lipschutz, SCHAUM
SERIES OUTLINES
CSE/IT
6/338
Guidelines and
Instructions for students
Examiner will set 9 questions in total.
Two questions from each section and one question
covering all sections which will be Q.1.
Q.1 is compulsory and of short answer type.
Each question carries equal mark (20 marks).
Students have to attempt 5 questions in total.
75% Attendance is compulsory.
Within the semester 3 Assignments and 11 Tutorials
would be given.
CSE/IT
7/338
Assignments
Assignment 1:
1. Explain constants,variable and data types in c
2. Explain User Defined Functions.
3. Differentiate between Structures and union
Assignment 2:
1. What are Pointers.Explain with example
2. Explain the use of malloc(),calloc(),realloc()
3. Explain Command line arguments
CSE/IT
8/338
Tutorial-1
Q1.C is a middle level language. Comment on it.
Q2.What are the different operators available in C.
Q3.Explain the syntax of IF, IF-ELSE, Construct in
detail.
Q4.Explain the syntax of switch case with
example.
CSE/IT
9/338
Tutorial-2
Q1.Explain the different loops available in c with an
example.
Q2.Explain user defined function with an example.
Q3.Difference between call by value and call by
reference.
Q4.Explain the different inbuilt functions available in c.
CSE/IT
10/338
Tutorial-3
Q1.Explain pointers with Character string.
Q2.Explain pointer to function.
Q3. What is the O/P:
Main(){int j,a[]= {10,20,30,40,50}
For (j=0;j<5;j++)
{ printf(%d,a);
A++;
}}
11/338
Section -A
CSE/IT
12/338
An Overview of Computer
Evolution of Computers
Hardware organization of computer
Introduction to microprocessor
Generations of microprocessors
Commonly used CPUs
Input/Output devices
Input/Output ports and connectors.
CSE/IT
13/338
Evolution of Computers
14/338
Cont
CSE/IT
15/338
Cont
CSE/IT
16/338
Cont
A computer as shown in Fig. performs basically five major operations or
functions irrespective of their size and make. That are: 1) It accepts data or instructions by way of input
2) It stores data
3) It can process data as required by the user
4) It gives results in the form of output
5) It controls all operations inside a computer
CSE/IT
17/338
Hardware Organization of
Computer
1.
2.
3.
4.
5.
CSE/IT
18/338
Input Device
CSE/IT
19/338
Output Device
Output devices receive information from the CPU and present it to the user
in the desired Form. Output devices include
display screen
loudspeakers,
printers, plotters, etc.
CSE/IT
20/338
CPU
CSE/IT
21/338
Memory Unit
CSE/IT
22/338
Control Unit
The control unit tells the rest of the computer system how to carry out a
programs instructions.
It directs the movement of electronic signals between memory which
temporarily holds data, instructions and processes information - and the ALU.
It also directs these control signals between the CPU and input/output devices.
CSE/IT
23/338
ALU
Arithmetic Logic Unit, usually called the ALU, performs two types of
operations
arithmetical
logical.
Arithmetical operations are the fundamental mathematical operations
consisting of
addition, subtraction, multiplication and division.
Logical operations consist of comparisons. That is two pieces of data are
compared to see whether one is
equal to, less than, or greater than the other.
CSE/IT
24/338
Introduction to
Microprocessor
CSE/IT
25/338
P1 (086) First-Generation
microprocessors
The first generation of processors represents the series of chips from Intel
that were found in the first PCs. IBM, as the architect of the PC at the time,
chose Intel processors and support chips to build the PC motherboard,
setting a standard that would hold for many subsequent processor
generations to come.
CSE/IT
26/338
CSE/IT
27/338
After Intel produced the 8086 and 8088 chips, it turned its sights toward
producing a more powerful chip with an increased instruction set. The
company's first efforts along this line - the 80186 and 80188 - were
unsuccessful. But incorporating system components into the CPU chip was
an important idea for Intel because it led to faster, better chips, such as the
286. The relationship between the 80186 and 80188 is the same as that of
the 8086 and 8088; one is a slightly more advanced version of the other.
Compared CPU to CPU, the 80186 is almost the same as the 8088 and has
a full 16-bit design. The 80188 (like the 8088) is a hybrid chip that
compromises the 16-bit design with an 8-bit external communications
interface. The advantage of the 80186 and 80188 is that they combine on a
single chip 15 to 20 of the 80868088 series system components - a fact
that can greatly reduce the number of components in a computer design.
The 80186 and 80188 chips were used for highly intelligent peripheral
adapter cards of that age, such as network adapters
CSE/IT
28/338
8087 Coprocessor
Intel introduced the 8086 processor in 1976. The math coprocessor that
was paired with the chip-the 8087-often was called the numeric data
processor (NDP), the math coprocessor, or simply the math chip. The 8087
is designed to perform high-level math operations at many times the speed
of the main processor. The primary advantage of using this chip is the
increased execution speed in number-crunching programs, such as
spreadsheet applications.
CSE/IT
29/338
CSE/IT
30/338
CPU socket
is the connector that interfaces between a computer's motherboard and
the processor itself. Most CPU sockets and processors in use today are
built around the pin grid array (PGA) architecture, in which the pins on
the underside of the processor are inserted into the socket, usually with
zero insertion force (ZIF) to aid installation. In contrast to this, a
couple current and upcoming sockets use a land grid array (LGA) in
which the pins are on the socket side instead and come in contact with
pads on the processor.
Slot
based processors are cartridge shaped and fix into a slot that looks
similar to expansion slots.
General
In general sockets and slots are used so that the Processor and the
motherboard of a computer are able to communicate with each other.
And it depends on the processor on what type of socket or slot that it
might use.
CSE/IT
31/338
Slot 1, Slot A, and Socket 7 are all various types of CPU (Central
Processing Unit) Interfaces. Interfaces are the connection points between
the motherboard and any add on or changeable components including
processor chips, peripherals, extension cards, etc. There are two main
types of interfacesslots and sockets.
Slot style interfaces accept Single Edge Contact (SEC) cartridges. An SEC
is a way to package microprocessors so that there is a slim single edge
which connects to the interface, allowing for perpendicular mounting to the
motherboard.
Socket style interfaces work on a principle or plug and socket similar to
that of a common wall socket. The component to be plugged into the
interface will have a Pin Grid Array (PGA)-a square chip package with a
pin pattern often of high density.
In the evolution of motherboards and CPU interfaces, the socket style
interface was the preference among manufactures until the mid to late 90s
when slots became the preferred interface. Although both are present in
the market, the current shift is back toward socket style CPU interfaces.
CSE/IT
32/338
Dual Processor
A computer that contains two CPUs. Dual processor systems (DP systems)
have two independent CPU chips and differ from a dual core system (DC
system), which has two processors built into the same CPU chip.
Not all operating systems or programs (for example Word) are able to
support dual processors.
CSE/IT
33/338
Quad Processor
CSE/IT
34/338
INPUT DEVICES
Parts of Computer, which are used to feed data and commands are called
Input Devices
Some Input Devices are:
Keyboard
Mouse
Joy Stick
Scanner
Voice Input System
CSE/IT
35/338
Cont
Keyboard is the most commonly used Input Device. The keys on the
keyboard can be classified as follows:
Alphabetic keys
Numeric keys
Function keys
Symbols keys
Special keys
CSE/IT
36/338
Cont
Mouse is a pointing device which is used to draw, move and resize the
picture and words. It has a small ball inside ,which when rolls, moves the
rollers, which move the pointer on the screen of monitor. it has two buttons
on the top
CSE/IT
37/338
Cont
A joystick consists of vertical bar. It can be rotated in various directions.
This rotation moves the cursor to the desired position.
CSE/IT
38/338
OUTPUT DEVICES
Output devices are the devices which are used to get final result of work
done on computer.
Following are some Output Devices:
Monitor or Visual Display Unit
Printers
Speakers
CSE/IT
39/338
Cont
CSE/IT
40/338
Cont
These days a lot of printers are available in the market which can be
divided as follows:
Impact Printers
Non-Impact Printers
CSE/IT
41/338
Cont
Speakers are used to listen sounds from a computer system. When you are
watching a cartoon film, the picture appears on the monitor, but you can
hear cartoon character talking only if speakers are attached to your
computer
CSE/IT
42/338
INPUT/OUTPUT PORTS
This is the standard input and output facilities in Isis. Input from and
output to any endpoint is handled using the same mechanism known as a
port, which allows the same procedures to be used for reading, writing, and
other operations, regardless of where the data is coming from or going to.
It will usually not be necessary to look at anything in this list, and of
course, nothing in the list should ever be modified manually.
CSE/IT
43/338
Cont
One can do the following - :
Open a port
Close a Port
Read and Write Data
Port Position
Port Status
Port Queries
Port Utilities
CSE/IT
44/338
CONNECTORS
The part of a cable that plugs into a port or interface to connect one device
to another. Most connectors are either male (containing one or more
exposed pins) or female (containing holes in which the male connector can
be inserted). Every house or office today is equipped with a multitude of
connectors. Connectors are devices used for mating and de-mating
electrical power connections. Connectors are responsible for power
transfers and information transfers among machines and people that are
spread over different locations.
All electronic devices require a constant source of power to function and
like all electronics even computers require power to function. Computer
PSU is a term given to any the wires that that convert lethal electricity into
usable and safe electricity. Each PSU requires connectors to function and
this article is going to elaborate on the connectors used in these power
supplies.
CSE/IT
45/338
Cont
CSE/IT
46/338
Introduction to Operating
system
CSE/IT
47/338
Introduction to Operating
System
CSE/IT
48/338
Functions of an Operating
System
Resource management
The resource management function of an OS allocates computer resources
such as CPU time, main memory, secondary storage, and input and output
devices for use.
Data management
The data management functions of an OS govern the input and output of the
data
and
their
location,
storage,
and
retrieval.
Job (task) management
The job management function of an OS prepares, schedules, controls, and
monitors jobs submitted for execution to ensure the most efficient
processing. A job is a collection of one or more related programs and their
data standard means of communication between user and computer.
CSE/IT
49/338
Cont
CSE/IT
50/338
Types of an Operating
System
CSE/IT
51/338
Introduction to MS-DOS
CSE/IT
52/338
Cont
The User Interface (shell)
- Conventional program that allows the user to interact with the
operating system.
- Default MS DOS user interface is a shell program called
Command.com
The MS-DOS Kernel
CSE/IT
53/338
MS-DOS Kernel
The kernel provides a collection of hardware-independent
services called system functions.
- File Management
- Memory Management
- Device Input and Output
- Process control
CSE/IT
54/338
File Management
Block Devices are accessed on a sector basis. The MS- DOS kernel
through the device driver sees a block as a logical fixed size array of
sectors. the device driver in turn translates the logical sector requests
from the MS DOS into physical locations on the block device.
MS DOS file system is divided into four parts
- Boot Sector
- Always at the beginning of a partition.
- Contains OEM identification, a loader routine , and a BIOS
parameter block
CSE/IT
55/338
Cont
- File Allocation Tables (FAT)
- Provides a map to the storage locations of files on the disk by
indicating which
clusters are allocated to each file.
- Second copy of FAT as back up.
- Free cluster is found by scanning the FAT for a zero value.
- Root directory
- Root directory entries are 32 bytes long.
- Each entry includes a filename and extension, size, starting FAT
entry, the time and date the
file was created and the files attributes.
CSE/IT
56/338
UNIX
CSE/IT
57/338
57
Logging In UNIX
CSE/IT
58/338
58
UNIX Shell
After a successful login, the shell program is run. The default shell of
bingsuns: tcsh
bingsun2% ps
PID TTY TIME CMD
2159 pts/2 0:00 tcsh
Shell is a command line interpreter that reads user commands and executes
them.
CSE/IT
59/338
59
Unix Shells
Common Shells: Bourne shell, the C shell, and the Korn shell.
The shell on bingsuns is tcsh (tc shell).
Users can switch between shells, using the commands bash, csh, ksh, sh.
Control D (^d) to return back to original shell, or just use the command:
exit.
CSE/IT
60/338
60
CSE/IT
61/338
61
CSE/IT
62/338
62
File System
CSE/IT
63/338
63
CSE/IT
64/338
64
UNIX Editors
CSE/IT
65/338
65
Starting Windows XP
Windows XP
Starts when computer is turned on
Elements of the desktop
Icon
Pointer
Desktop
Date/Time control
Taskbar
Start button
Notification area
CSE/IT
66/338
Starting Windows XP
67/338
Starting Windows XP
CSE/IT
68/338
Desktop
Area that appears on the screen when Windows XP starts
A workspace for projects and tools
Uses default settings when the computer is first started
Default settings: settings preset by the operating system
Appearance can be changed by the user
CSE/IT
69/338
A pointing device
Helps the user interact with objects on the computer screen
Comes in many shapes and sizes
Mouse
Most common pointing device
CSE/IT
70/338
Anatomy of a Window
Controls
Located in a window
Graphical or textual objects used for
Manipulating the window
Using the program
Examples
Menu bar
Sizing buttons
Status bar
Title bar
Toolbar
Workspace
CSE/IT
71/338
SECTION-2
Basic Introduction to System Software and Programs
Basic Introduction to Computer Networks
CSE/IT
72/338
73/338
Introduction to Programming
Language
CSE/IT
74/338
Characteristics of good
Programming Language
1. Clarity of source code the extent to which inherent language features
support source code that is readable and understandable and that clearly
reflects the underlying logical structure of the program.
2. Complexity management (architecture support) the extent to which
inherent language features support the management of system complexity,
in terms of addressing issues of data, algorithm, interface, and architectural
complexity.
3. Concurrency support the extent to which inherent language features
support the construction of code with multiple threads of control (also
known as parallel processing).
4. Distributed system support the extent to which inherent language features
support the construction of code to be distributed across multiple platforms
on a network.
5. Maintainability the extent to which inherent language features support the
construction of code that can be readily modified to satisfy new
requirements or to correct deficiencies.
CSE/IT
75/338
Cont
6. Mixed language support the extent to which inherent language features
support interfacing to other languages.
7. Object-oriented programming support the extent to which inherent
language features support the construction of object-oriented code.
8. Portability the extent to which inherent language features support the
transfer of a program from one hardware and/or software platform to
another.
9. Real-time support the extent to which inherent language features support
the construction of real-time systems
CSE/IT
76/338
Machine Language
The lowest-level programming language (except for computers that utilize
programmable microcode) Machine languages are the only languages
understood by computers.
While easily understood by computers, machine languages are almost
impossible for humans to use because they consist entirely of numbers.
Programmers, therefore, use either a high-level programming language or
an assembly language. An assembly language contains the same
instructions as a machine language, but the instructions and variables have
names instead of being just numbers.
CSE/IT
77/338
Advantages of Machine
language
It is a most efficient in term of storage area use and execution speed and
it also allows programmer to utilize the computer's potential for
processing data.
The only advantage is that program of machine language run very fast
because no translation program is required for the CPU.
In machine language, the very basic and specific commands may be
used, like to where the specific data will be stored, how operations and
functions be carried out. and since it is in a code the machine can
understand, it may not need a compiler.
CSE/IT
78/338
Disadvantages of Machine
Language
1. It is very difficult to program in machine language. The programmer has to
know details of hardware to write program.
2. The programmer has to remember a lot of codes to write a program which
results in program errors.
3. It is difficult to debug the program
CSE/IT
79/338
Assembly language
Each type of CPU has its own machine language and assembly language,
so an assembly language program written for one type of CPU won't run
on another. In the early days of programming, all programs were written in
assembly language.
CSE/IT
80/338
Comparison Between
Assembly & Machine
Language
Machine language is the actual bits used to control the processor in the
computer, usually viewed as a sequence of hexadecimal numbers (typically
bytes).
Assembly language is a more human readable view of machine language.
Instead of representing the machine language as numbers, the instructions
and registers are given names (typically abbreviated words, or mnemonics,
eg ld means "load").
An assembly language program (ie a text file) is translated to machine
language by an assembler. A disassembler performs the reverse function.
Machine language faster than assembly language even than assembly
language depend upon machine language
CSE/IT
81/338
Advantage of Assembly
language
CSE/IT
82/338
Disadvantage of Assembly
language
CSE/IT
83/338
CSE/IT
84/338
CSE/IT
85/338
Cont
High level language programs require less time and efforts that due the
preparation cost of the program.
High level programs are very easy to maintain than lower level
languages. In lower level languages instruction are difficult and very
hard to locate, correct and modify but in high level languages it is very
easy to understand and modify when desired.
In high level languages programmer needs not to write all steps because
computer take cares of all small error. Compilers of high level languages
automatically catch and point out the errors made by the programmers.
CSE/IT
86/338
Disadvantages of High
Level Language
87/338
CSE/IT
88/338
CSE/IT
89/338
Compilation
CSE/IT
90/338
Compilation
CSE/IT
91/338
Cont..
CSE/IT
92/338
Symbol Table
93/338
Literal table
CSE/IT
94/338
Parse tree
CSE/IT
95/338
Interpreter
CSE/IT
96/338
Cont C
CSE/IT
97/338
Compiler characteristics
CSE/IT
98/338
Interpreter characteristics:
CSE/IT
99/338
Assemblers
There are two main classes of programming languages: high level (e.g., C,
Pascal) and low level. Assembly Language is a low level programming
language. Programmers code symbolic instructions, each of which
generates machine instructions.
CSE/IT
100/338
Advantages of coding in
assembly language
CSE/IT
101/338
Disadvantages of coding in
assembly language
Not portable
More complex
Requires understanding of hardware details (interfaces)
CSE/IT
102/338
Assembler
1. Generate machine instructions
evaluate the mnemonics to produce their machine code
evaluate the symbols, literals, addresses to produce their equivalent
machine addresses
convert the data constants into their machine representations
2. Process pseudo operations
CSE/IT
103/338
CSE/IT
104/338
Data Structures
Location counter (LC): points to the next location where the code will be
placed
Op-code translation table: contains symbolic instructions, their lengths and
their op-codes (or subroutine to use for translation)
Symbol table (ST): contains labels and their values
String storage buffer (SSB): contains ASCII characters for the strings
Configuration table: contains pointer to the string in SSB and offset where
its value will be inserted in the object code
CSE/IT
105/338
Cont
CSE/IT
106/338
Linker
On UNIX variants the term loader is often used as a synonym for linker.
Other terminology was in use, too. For example, on SINTRAN III the
process performed by a linker (assembling object files into a program) was
called loading (as in loading executable code onto a file). Because this
usage blurs the distinction between the compile-time process and the runtime process, this article will use linking for the former and loading for the
latter. However, in some operating systems the same program handles both
the jobs of linking and loading a program.
CSE/IT
107/338
Cont
CSE/IT
108/338
Cont
Linkers can take objects from a collection called a library. Some linkers do
not include the whole library in the output; they only include its symbols
that are referenced from other object files or libraries. Libraries exist for
diverse purposes, and one or more system libraries are usually linked in by
default.
The linker also takes care of arranging the objects in a program's address
space. This may involve relocating code that assumes a specific base
address to another base. Since a compiler seldom knows where an object
will reside, it often assumes a fixed base location (for example, zero).
Relocating machine code may involve re-targeting of absolute jumps, loads
and stores
CSE/IT
109/338
Dynamic linking
CSE/IT
110/338
Advantages
CSE/IT
111/338
Disadvantages
CSE/IT
112/338
Loader
Part of the OS that brings an executable file residing on disk into memory
and starts it running
Steps -:
Read executable files header to determine the size of text and data
segments
Create a new address space for the program
Copies instructions and data into address space
Copies arguments passed to the program on the stack
Initializes the machine registers including the stack ptr
Jumps to a startup routine that copies the programs arguments from the
stack to registers and calls the programs main routine
CSE/IT
113/338
Data Communication
Modulation
Network devices
LAN, LAN topologies
WAN,
OSI Reference model
TCP/IP Reference model,
Backbone network
Network connecting devices,
HTTP
DNS
Network Security
CSE/IT
114/338
CSE/IT
115/338
History of Data
Communication
CSE/IT
116/338
Features of Communication
CSE/IT
117/338
Cont.
CSE/IT
118/338
Network Applications
CSE/IT
119/338
Batch applications
Data entry applications
Distributed applications
Inquiry/response applications
CSE/IT
Interactive applications
Sensor-based applications
Combined applications
120/338
Introduction to Modulation
CSE/IT
121/338
Contd.
CSE/IT
122/338
Encoding
and
Contd.
Modulation Techniques
CSE/IT
123/338
2/45
Cont
Types of Modulation
Amplitude Modulation
Frequency Modulation
Phase Modulation
CSE/IT
124/338
Frequency Modulation
(FM)
CSE/IT
125/338
Frequency Modulation
CSE/IT
126/338
One of the property of a sine wave is its phase, the offset from a reference time
at which the sine wave begins
It is possible to use changes in phase to represent a signal
We use the term phase shift to characterize such changes
If phase changes after cycle k, the next sine wave will start slightly later than
the time at which cycle k completes
A slight delay resembles a change in frequency
PM can be thought of as a special form of frequency modulation
However, phase shifts are important when a digital signal is used to
modulate a carrier
CSE/IT
127/338
CSE/IT
128/338
Networking Devices
CSE/IT
129/338
Cont
CSE/IT
130/338
Cont
CSE/IT
131/338
Router
ROUTER: a specialized network device that determines the next network point to
which it can forward a data packet towards the destination of the packet. Unlike a
gateway, it cannot interface different protocols. Works on OSI layer 3.
CSE/IT
132/338
Bridge
BRIDGE : a device that connects multiple network segments along the data link layer
Works on OSI layer 2.
CSE/IT
133/338
Hub
HUB : connects multiple Ethernet segments together making them act as a single
segment. When using a hub, every attached device shares the same broadcast domain
and the same collision domain . Therefore, only one computer connected to the hub is
able to transmit at a time. Depending on the network topology, the hub provides a basic
level 1 OSI model connection among the network objects (workstations, servers, etc.).
It provides bandwidth which is shared among all the objects, compared to switches,
which provide a connection between individual nodes. Works on OSI layer 1.
CSE/IT
134/338
Repeater
REPEATER: device to amplify or regenerate digital signals received while sending
them from one part of a network into another. Works on OSI layer 1.
CSE/IT
135/338
CSE/IT
136/338
CSE/IT
137/338
LAN Topologies
Bus
Ring
Star
CSE/IT
138/338
Bus Topology - 1
Stations attach to linear medium (bus)
Via a tap - allows for transmission
and reception
Transmission propagates in medium in
both directions
Received by all other stations
Not addressed stations ignore
Need to identify target station
Each station has unique address
Destination address included in frame
header
Terminator absorbs frames at the end of
medium
CSE/IT
139/338
Bus Topology - 2
CSE/IT
140/338
Ring Topology
Repeaters
joined
by
pointto-point links in closed loop
Links unidirectional
Receive data on one link and
retransmit on another
Stations attach to repeaters
Data transmitted in frames
Frame passes all stations in a
circular manner
Destination recognizes address
and copies frame
Frame circulates back to source
where it is removed
Medium access control is needed to
determine when station can insert
frame
CSE/IT
141/338
CSE/IT
142/338
Star Topology
Each
station
connected
directly to central node
using
a
full-duplex
(bi-directional) link
Central node can broadcast (hub)
Physical star, but logically like
bus since broadcast
Only one station can transmit at
a time
Central node can act as frame
switch
retransmits only to destination
todays technology
CSE/IT
Hub or Switch
143/338
CSE/IT
144/338
Normally WANs are just physical extensions of LANs. They are built
using private leased lines. Their huge coverage area makes the cost go
higher and transmission speeds to drop down.
CSE/IT
145/338
There are two main components when the Wide Area Networks are considered.
1.Switching elements
2.Transmission lines
Let us start with what transmission lines are. Simply put transmission lines is a a
medium to transfers bits of information between the machines in the network.
To connect these transmission lines, we use specialized computers called
switching elements. It performs intelligent switching function. When it receives
an input packet, it decides which output line to forward it to. You should note that
that subnet mentioned here is a little ambiguous. Subnet here and subnetting for
network address is not the same. Here, the term subnet is used as a generic term
for computer components in the WAN.
CSE/IT
146/338
WAN Connection
Types
Leased line a pre-established WAN communications path from the
CPE, through the DCE switch, to the CPE of the remote site, allowing
DTE networks to communicate at any time with no setup procedures
before transmitting data.
Circuit switching uses dial-up modems or ISDN and is used for lowbandwidth data transfers. Think phone call.
Packet switching allows you to share bandwidth with other companies
to save money. Can be thought of as a network thats designed to look like
a leased line, yet costs more like circuit switching.
CSE/IT
147/338
CSE/IT
148/338
CSE/IT
149/338
150/338
CSE/IT
151/338
Note that the OSI model itself is not a network architecture, because it
does not specify the exact services and protocols to be used in each layer.
It just tells what each layer should do.
However, ISO has also produced standards for all the layers, although
these are not part of the reference model itself. Each one has been
published as a separate international standard.
Next, we will discuss each layer of the model in turn, starting at the
bottom layer.
CSE/IT
152/338
153/338
The main task of the data link layer is to take a raw transmission facility
and transform it into a line that appears free of undetected transmission
errors to the network layer.
It accomplishes this task by having the sender break the input data up into
data frames (typically a few hundred or a few thousand bytes), transmit the
frames sequentially, and process the acknowledgment frames sent back by
the receiver.
Since the physical layer merely accepts and transmits a stream of bits
without any regard to meaning or structure, it is up to the data link layer to
create and recognize frame boundaries.
This can be accomplished by attaching special bit patterns to the beginning
and end of the frame. (if these bit patterns accidentally occur in the data,
special care must be taken to make sure these patterns are not incorrectly
interpreted as frame delimiters.)
CSE/IT
154/338
A noise burst on the line can destroy a frame completely. In this case, the
data link layer software on the source machine can retransmit the frame.
However, multiple transmissions of the same frame introduce the
possibility of duplicate frames. (if the acknowledgment frame from the
receiver back to the sender was lost)
It is up to this layer to solve the problems caused by damaged, lost and
duplicate frames.
Another issue that arises in the data link layer (and most higher layers as
well) is how to keep a fast transmitter from drowning a slow receiver in
data. Some traffic regulation mechanism must be employed to let the
transmitter know how much buffer space the receiver has at the moment.
Frequently, this flow regulation and error handling are integrated.
CSE/IT
155/338
A key design issue with the network layer is determining how packets are
routed from source to destination.
Routes can be based on static tables that are wired into the network
and rarely changed.
They can also be determined at the start of each conversation, for
example a terminal session.
Finally, the can be highly dynamic, being determined anew for each
packet, to reflect the current network load.
If too many packets are present in the communication line at the same
time, they will get in each others way, forming bottlenecks. The control of
such congestion also belongs to the network layer.
There is often some accounting function built into the network layer. At
the very least, the software must count how many packets or characters or
bits are sent by each customer, to produce billing information. When a
packet crosses a national border, with different rates on each side, the
accounting can become complicated.
CSE/IT
156/338
Cont
When a packet has to travel from one network to another to get to its
destination, many problems can arise:
The addressing used by the second network may be different from the
first one
The second one may not accept the packet at all because it is too large
The protocols may differ, and so on
CSE/IT
157/338
The basic function of the transport layer is to accept data from the session
layer, split it up into smaller units if need be, pass these to the network
layer, and ensure that the pieces all arrive correctly at the other end.
Furthermore, all this must be done efficiently, and in a way that isolates
the upper layers from the inevitable changes in the hardware technology.
CSE/IT
158/338
Cont
The transport layer also determines what type of service to provide the
session layer, and ultimately, the users of the network:
The most popular type of transport connection is an error-free pointto-point channel that delivers messages or bytes in the order in which
they were sent.
However, other possible kinds of transport service are transport of
isolated messages with no guarantee about the order of delivery, and
broadcasting of messages to multiple destinations.
CSE/IT
159/338
CSE/IT
160/338
CSE/IT
161/338
CSE/IT
162/338
CSE/IT
163/338
The presentation layer manages these abstract data structures and converts
from the representation used inside the computer to the network standard
representation and back.
CSE/IT
164/338
CSE/IT
165/338
It also hides all other layers from programmers, and makes using a
network application transparent to the user
CSE/IT
166/338
CSE/IT
167/338
The sending process has some data it wants to send to the receiving
process.
It gives the data to the application layers, which then attaches the
application header AH to the front of it and gives the resulting item to the
presentation layer.
The presentation layer may transform this item in various ways, and
possibly add a header to the front, giving the result to the session layer. It
is important to note that the presentation layer is not aware which portion
of the item is AH and which is user data.
This process is repeated until the data reach the physical layer, where they
are actually transmitted to the receiving machine.
CSE/IT
168/338
For example, when the sending transport layer gets a message from the
session layer, it attaches a transport header (with information to be used by
the receiving transport layer) and sends it to the receiving transport layer.
From its point of view, the fact that it must actually hand the message to
the network layer on its own machine is an unimportant technicality.
CSE/IT
169/338
Let us now turn from the OSI reference model to the reference model used
in the grandparent of all computer networks, the ARPANET, and its
successor, the worldwide Internet.
Although TCP/IP was originally intended for the ARPANET, and currently
used in the Internet, it has become so popular that many local networks
(LANs) are using it as their protocols as well. Thus, we would like to
review this model as well.
The ARPANET was a research network sponsored by the DoD (U.S.
Department of Defense). It eventually connected hundreds of universities
and government installations using leased telephone lines. When satellite
and radio networks were added later, the existing protocols had trouble
internetworking with them, so a new reference architecture was needed.
CSE/IT
170/338
CSE/IT
171/338
CSE/IT
172/338
The analogy here is with the mail system. A person can drop a sequence of
international letters into a mail box in one country, and most of them will
be delivered to the correct address in the destination country. Probably the
letters will travel through one or more international mail gateways along
the way, but this is transparent to the users. Furthermore, the letters may
arrive out of order, and each country (i.e. network) has its own stamps,
preferred envelope sizes, and delivery rules, which is also hidden from the
users.
The internet layer defines an official packet format and protocol called IP
(Internet Protocol). The job of the internet layer is to deliver IP packets
where they are supposed to go. Packet routing is clearly the major issue
here, as is avoiding congestion. For these reasons, we can say that the
TCP/IP internet layer is very similar to the OSI network layer. Fig. 3.
shows the correspondence
CSE/IT
173/338
TCP/IP
Application
Application
Presentation
Session
Transport
Transport
Network
Internet
Data Link
Host-to-network
Physical
CSE/ITmodel
The TCP/IP reference
174/338
The layer above the internet layer in the TCP/IP model is now usually
called the transport layer.
It is designed to allow peer entities on the source and destination hosts
to carry on a conversation, the same as the OSI transport layer.
Two end-to-end protocols have been defined here:
1.
TCP (Transmission Control Protocol) is a reliable connectionoriented protocol that allows a byte stream originating on one
machine to be delivered without errors on any other machine in the
internet. It fragments the incoming byte stream into discrete
messages and passes each one onto the internet layer. At the
destination, the receiving TCP process reassembles the received
messages into the output stream. TCP also handles flow control to
make sure a fast sender cannot swamp a slow receiver with more
messages than it can handle.
CSE/IT
175/338
CSE/IT
176/338
CSE/IT
177/338
Many other protocols have been added to these over the years, such as:
the DNS (Domain Name Service) for mapping host names onto
their network addresses
CSE/IT
178/338
The OSI and TCP/IP reference models have much in common. Both are
based on the concept of a stack of independent protocols. Also, the
functionality of the layers is roughly similar.
Despite the fundamental similarities, the two models also have many
differences.
Probably the biggest contribution of the OSI model is to make the
distinction between the Services, Interfaces, and Protocols explicit.
These ideas fit very nicely with modern ideas about object-oriented
programming. An object, like a layer, has a set of methods (operations)
that can be invoked outside the object. The semantics of these methods
define the set of services that the object offers.
CSE/IT
179/338
The OSI reference model was devised before the protocols were
invented.
With the TCP/IP the reverse is true: the protocols came first, and the
model was really just a description of the existing protocols. There was
no problem with the protocols fitting the model: they fit perfectly. The
only trouble was that the model did not fit any other protocol stacks.
CSE/IT
180/338
despite its problems, the OSI model (minus the session and presentation
layers) has proven to be exceptionally useful for discussing computer
networks. In contrast, the OSI protocols have not become popular.
CSE/IT
181/338
HTTP vs HTML
CSE/IT
182/338
What is a protocol?
CSE/IT
183/338
An HTTP
conversation
Client
Server
OK
Display response
Close connection
OK
CSE/IT
184/338
An HTTP Example
The message requesting a Web page must begin with the work GET and be
followed by a space and the location of a file on the server, like this:
GET /fac/lpress/shortbio.htm
The protocol spells out the exact message format, so any Web client can
retrieve pages from any Web server.
CSE/IT
185/338
Network protocols
CSE/IT
186/338
CSE/IT
187/338
CSE/IT
188/338
Concept: Resource
Records
The DNS maps names into data using Resource Records.
Resource Record
www.ripe.net.
A 10.10.10.2
Address Resource
CSE/IT
189/338
ws1 ws2
ftp
www disi
www
branches.
ripe isi
tislabs
moon
google
net educom
CSE/IT
190/338
Concept: Domains
com doma
ripe
disi
www
ftp
net domain
ws2
CSE/IT
ripe.net domain
google
isi sun tislabs
moon
www
ws1
191/338
What is Security
Dictionary.com says:
1. Freedom from risk or danger; safety.
2. Freedom from doubt, anxiety, or fear; confidence.
3. Something that gives or assures safety, as:
1. A group or department of private guards: Call building security
if a visitor acts suspicious.
2. Measures adopted by a government to prevent espionage,
sabotage, or attack.
3. Measures adopted, as by a business or homeowner, to prevent a
crime such as burglary or assault: Security was lax at the firm's
smaller plant.
etc.
CSE/IT
192/338
Protect vital information while still allowing access to those who need it
Trade secrets, medical records, etc.
Provide authentication and access control for resources
Ex: AFS
Guarantee availability of resources
Ex: 5 9s (99.999% reliability)
CSE/IT
193/338
Cont
CSE/IT
194/338
CSE/IT
195/338
Section -C
CSE/IT
196/338
Overview of C
C is developed by Dennis Ritchie
C is a structured programming language
C supports functions that enables easy maintainability
of code, by breaking large file into smaller modules
Comments in C provides easy readability
C is a powerful language
CSE/IT
197/338
Program structure
A sample C Program
#include<stdio.h>
int main()
{
--other statements
}
CSE/IT
198/338
Header files
The files that are specified in the include section is
called as header file
These are precompiled files that has some functions
defined in them
We can call those functions in our program by
supplying parameters
Header file is given an extension .h
C Source file is given an extension .c
CSE/IT
199/338
Main function
This is the entry point of a program
When a file is executed, the start point is the main
function
From main function the flow goes as per the
programmers choice.
There may or may not be other functions written by
user in a program
Main function is compulsory for any c program
CSE/IT
200/338
201/338
Running a C Program
Type a program
Save it
Compile the program This will generate an exe file
(executable)
Run the program (Actually the exe created out of
compilation will run and not the .c file)
In different compiler we have different option for
compiling and running. We give only the concepts.
CSE/IT
202/338
Comments in C
Single line comment
// (double slash)
Termination of comment is by pressing enter key
Multi line comment
/*.
.*/
This can span over to multiple lines
CSE/IT
203/338
Data types in C
Primitive data types
int, float, double, char
204/338
Variables
Variables are data that will keep on changing
Declaration
<<Data type>> <<variable name>>;
int a;
Definition
<<varname>>=<<value>>;
a=10;
Usage
<<varname>>
a=a+1; //increments the value of a by 1
CSE/IT
205/338
CSE/IT
206/338
CSE/IT
207/338
For loops
The syntax of for loop is
for(initialisation;condition checking;increment)
{
set of statements
}
Eg: Program to print Hello 10 times
for(I=0;I<10;I++)
{
printf(Hello);
}
CSE/IT
208/338
While loop
The syntax for while loop
while(condn)
{
statements;
}
Eg:
a=10;
while(a != 0) Output: 10987654321
{
printf(%d,a);
a--;
}
CSE/IT
209/338
Do While loop
The syntax of do while loop
do
{
set of statements
}while(condn);
Eg:
i=10;
Output:
do 10987654321
{
printf(%d,i);
i--;
}while(i!=0)
CSE/IT
210/338
Conditional statements
if (condition)
{
stmt 1;
}
else
{
stmt 2;
}
CSE/IT
211/338
Conditional statement
switch(var)
{
case 1: //if var=1 this case executes
stmt;
break;
case 2: //if var=2 this case executes
stmt;
break;
default:
//if var is something else this will execute
stmt;
}
CSE/IT
212/338
Operators
Arithmetic (+,-,*,/,%)
Relational (<,>,<=,>=,==,!=)
Logical (&&,||,!)
Bitwise (&,|)
Assignment (=)
Compound assignment(+=,*=,-=,/=,%=,&=,|=)
Shift (right shift >>, left shift <<)
CSE/IT
213/338
String functions
CSE/IT
214/338
Numeric functions
CSE/IT
215/338
Procedures
Procedure is a function whose return type is void
Functions will have return types int, char, double,
float or even structs and arrays
Return type is the data type of the value that is
returned to the calling point after the called function
execution completes
CSE/IT
216/338
Functions and
Parameters
Syntax of function
Declaration section
<<Returntype>> funname(parameter list);
Definition section
<<Returntype>> funname(parameter list)
{
body of the function
}
Function Call
Funname(parameter);
CSE/IT
217/338
Example function
#include<stdio.h>
void fun(int a);
int main()
{
fun(10);
}
void fun(int x)
{
printf(%d,x);
}
//declaration
//Call
//definition
CSE/IT
218/338
CSE/IT
219/338
Arrays
Arrays fall under aggregate data type
Aggregate More than 1
Arrays are collection of data that belong to same data
type
Arrays are collection of homogeneous data
Array elements can be accessed by its position in the
array called as index
CSE/IT
220/338
Arrays
Array index starts with zero
The last index in an array is num 1 where num is
the no of elements in a array
int a[5] is an array that stores 5 integers
a[0] is the first element where as a[4] is the fifth
element
CSE/IT
221/338
Multidimensional Arrays
We can also have arrays with more than one
dimension
float a[5][5] is a two dimensional array. It can store
5x5 = 25 floating point numbers
The bounds are a[0][0] to a[4][4]
CSE/IT
222/338
Structures
Structures are user defined data types
It is a collection of heterogeneous data
It can have integer, float, double or character data in it
We can also have array of structures
struct <<structname>>
{
members;
}element;
We can access element.members;
CSE/IT
223/338
Structures
Collections of related variables (aggregates) under
one name
Can contain variables of different data types
Commonly used to define records to be stored in
files
Combined with pointers, can create linked lists,
stacks, queues, and trees
CSE/IT
224/338
Structure Definitions
Example
struct card {
char *face;
char *suit;
};
225/338
Structure Definitions
struct information
A struct cannot contain an instance of itself
Can contain a member that is a pointer to the same
structure type
A structure definition does not reserve space in
memory
Instead creates a new data type used to declare
structure variables
CSE/IT
226/338
Continued..
Declarations
Declared like other variables:
card oneCard, deck[ 52 ], *cPtr;
Can use a comma separated list:
struct card {
char *face;
char *suit;
} oneCard, deck[ 52 ], *cPtr;
CSE/IT
227/338
Structure Definitions
Valid Operations
Assigning a structure to a structure of the same
type
Taking the address (&) of a structure
Accessing the members of a structure
Using the sizeof operator to determine the size
of a structure
CSE/IT
228/338
Initializing Structures
Initializer lists
Example:card oneCard = { "Three", "Hearts" };
Assignment statements
Example: card threeHearts = oneCard;
Could also declare and initialize threeHearts as
follows:
card threeHearts;
threeHearts.face = Three;
threeHearts.suit = Hearts;
CSE/IT
229/338
Accessing Members of
Structures
Accessing structure members
Dot operator (.) used with structure variables
card myCard;
printf( "%s", myCard.suit );
Arrow operator (->) used with pointers to structure
variables
card *myCardPtr = &myCard;
printf( "%s", myCardPtr->suit );
myCardPtr->suit is equivalent to
( *myCardPtr ).suit
CSE/IT
230/338
231/338
Arrays of Structure
Since structures are data types that are especially useful for
creating collection items, make a collection of them using an
array. Let us now take an example to use an array of structures
rather than individual ones.\
object2.c:
#include <stdio.h>
#include <stdlib.h>
struct object {
char id[20];
int xpos;
int ypos;
};
CSE/IT
232/338
Continue
struct object createobj(char id[], int xpos, int ypos);
void printobj(struct object obj);
void main() {
int i;
struct object gameobjs[2];
gameobjs[0] = createobj("player1", 0, 0);
gameobjs[1] = createobj("enemy1", 2, 3)
for (i = 0; i < 2; i++)
printobj(gameobjs[i]);
//update enemy1 position
gameobjs[1].xpos = 1;
gameobjs[1].ypos = 2;
CSE/IT
233/338
Continue
for (i = 0; i < 2; i++)
printobj(gameobjs[i]);
}
struct object createobj(char id[], int xpos, int ypos) {
struct object newobj;
strcpy(newobj.id, id);
newobj.xpos = xpos;
newobj.ypos = ypos;
return newobj;
}
CSE/IT
234/338
Continue
void printobj(struct object obj) {
printf("name: %s, ", obj.id);
printf("x position: %d, ", obj.xpos);
printf("y position: %d", obj.ypos);
printf("\n");
}
235/338
Structure within a
Structure
Structures may even have structures as members.
Imagine (x, y) coordinate pair is a structure called
coordinates. Redeclare the object structure as follows:
struct object {
char id[20];
struct coordinates loc;
};
Initialize these by using nested braces :
struct object player1 = {player1, {0, 0}};
CSE/IT
236/338
Continue
To access or set members of the above internal structure do like
this:
struct object player1;
player1.id = player1;
player1.loc.xpos = 0;
player1.loc.ypos = 0;
CSE/IT
237/338
Type def
typedef
Creates synonyms (aliases) for previously defined
data types
Use typedef to create shorter type names
Example:
typedef struct Card *CardPtr;
238/338
Type def
The typedef operator is used for creating alias of a
data type
For example I have this statement
typedef int integer;
Now I can use integer in place of int
i.e instead of declaring int a;, I can use
integer a;
This is applied for structures too.
CSE/IT
239/338
Unions
Unions and Structures are identical in all ways,
except for one very important aspect. Only one
element in the union may have a value set at any
given time.
Unions are mainly used to conserve memory. While
each member within a structure is assigned its own
unique storage area, the members that compose a
union share the common storage area within the
memory.
Unions are useful for application involving multiple
members where values are not assigned to all the
members at any one time.
CSE/IT
240/338
Continue..
Let us modify structure object from above so that it has
a union for indicating dead or alive in it:
struct object {
char id[20];
struct coordinates loc;
union deadoralive {
int alive;
int dead;
}
};
CSE/IT
241/338
Section -D
CSE/IT
242/338
Pointers
Pointer is a special variable that stores address of
another variable
Addresses are integers. Hence pointer stores integer
data
Size of pointer = size of int
Pointer that stores address of integer variable is called
as integer pointer and is declared as int *ip;
CSE/IT
243/338
Pointers
Pointers that store address of a double, char and float
are called as double pointer, character pointer and
float pointer respectively.
char *cp
float *fp
double *dp;
Assigning value to a pointer
int *ip = &a; //a is an int already declared
CSE/IT
244/338
Examples
int a;
a=10;
int *ip;
ip = &a;
//a stores 10
//ip stores address of a (say 1000)
ip :
fetches 1000
*ip :
fetches 10
* Is called as dereferencing operator
CSE/IT
245/338
Call by Value
Calling a function with parameters passed as values
int a=10;
fun(a);
void fun(int a)
{
defn;
}
Here fun(a) is a call by value.
Any modification done with in the function is local to it
and will not be effected outside the function
CSE/IT
246/338
Call by reference
Calling a function by passing pointers as parameters
(address of variables is passed instead of variables)
int a=1;
fun(&a);
247/338
a=10
a=10
x=10
x=11
CSE/IT
248/338
Explanation
CSE/IT
249/338
a=10
a=11
x=10
x=11
CSE/IT
250/338
Explanation
251/338
Conclusion
Call by value => copying value of variable in another
variable. So any change made in the copy will not
affect the original location.
Call by reference => Creating link for the parameter
to the original location. Since the address is same,
changes to the parameter will refer to original
location and the value will be over written.
CSE/IT
252/338
CSE/IT
253/338
Outline
Memory management
Dynamic memory allocation
Functions: malloc, calloc, realloc
De-allocating memory
Functions: free
CSE/IT
254/338
Dynamic memory
allocation in C
Stack-allocated memory
When a function is called, memory is allocated for
all of its parameters and local variables.
Each active function call has memory on the stack
(with the current function call on top)
When a function call terminates,
255/338
Dynamic memory
allocation in C
Heap-allocated memory
This is used for persistent data, that must survive
beyond the lifetime of a function call
global variables
dynamically allocated memory C statements can
create new heap data (similar to new in Java/C++)
Heap memory is allocated in a more complex way than
stack memory
Like stack-allocated memory, the underlying system
determines where to get more memory the
programmer doesnt have to search for free memory
space!
CSE/IT
256/338
Dynamic Memory
Two different ways to look at memory
allocation:
Transparent to user
Done by the compiler as well as the OS.
User-defined
Memory allocated by the user.
CSE/IT
257/338
Dynamic Memory
(contd.)
Why allocate memory ??
Required by program for permanent variables.
Compiler arranges for memory at compiler
time.
OS + program allocate memory at run time.
Memory exists for life of program.
CSE/IT
258/338
Dynamic Memory
(contd.)
Why allocate memory ??
Reserve working space for program.
Working space is space required for execution
of program instructions (e.g: arithmetic, logical
operations).
Normally maintained using a stack or a heap.
CSE/IT
259/338
Dynamic Memory
(contd.)
Stacks and heaps:
Data structures with specific purposes.
A stack is an organized data structure, which
follows the LIFO (Last In First Out)
principle.
A data item which enters the stack last is the first
to be taken out.
260/338
HEAP Manipulation
1
After removal
CSE/IT
261/338
STACK Manipulation
5
4
After removal
1
CSE/IT
262/338
Dynamic Memory
(contd.)
Why do we need dynamic allocation ?????
There are times when we dont know how much
memory is required.
Employee data base that sorts employee records
and adds new employees.
Program accepting command line input defining
size of matrices.
Directory trees where files/folders can be
added/deleted.
CSE/IT
263/338
Dynamic Memory
(contd.)
Programmer arranges to allocate appropriate amount
of memory.
Reads command line arguments.
Processes input flag to add new record to database.
CSE/IT
264/338
Dynamic Memory
(contd.)
E.g:
char response;
printf (Add a new record y/n ?);
scanf (%c, &response);
if (response == y || response == Y)
{allocate required memory}
CSE/IT
265/338
Dynamic Memory
(contd.)
Also used by the OS !!!
Heap is managed dynamically through the use of
dynamic memory.
Used mostly to calculate the values of expressions,
assign memory blocks etc.
Stacks are also managed dynamically.
Used mostly for function calls, scope of variables
etc.
CSE/IT
266/338
Dynamic Memory
(contd.)
Functions available to allocate memory:
void *malloc (size_t size)
Returns a void pointer to a contiguous block in
memory of size equal to size bytes.
** Size is always taken to be in bytes.
CSE/IT
267/338
Dynamic Memory
(contd.)
E.g: x = malloc (10);
If successful, returns address of the block of 10
bytes in memory.
x points to the beginning of this block of mem.
268/338
Allocating a block of
memory :malloc
On success returns pointer (address of beginning of
block of memory just created).
On error, returns NULL (keyword in C).
Errors:
Insufficient block size.
size = 0.
CSE/IT
269/338
malloc (contd.)
Memory is allocated from the heap.
Allocated space is not initialized, so contains
garbage.
No connection exists with type of data to be stored in
the memory space just created.
Contained in the header file: stdlib.h or alloc.h
CSE/IT
270/338
malloc (contd.)
Why is a void pointer returned ???
malloc just allocates memory which consists of
some number of bytes.
Memory as such has no data type, unless the user
or the running program chooses to associate a data
type with the block of memory just created.
CSE/IT
271/338
malloc (contd.)
How to assign a data type to the memory just
created ???
Use type casting.
Once type cast to a data type, memory takes on the
meaning of that data type.
Amount of data types that can be represented
depends on the size of the data type.
CSE/IT
272/338
malloc (contd.)
E.g:
double *x; // x is a pointer to double as malloc
returns an address.
x = (double *) malloc (100); // type casting the
memory to be of type pointer to double.
No. of doubles = 100/8 = 12 !!!
We can clearly see a pit fall of malloc out here.
CSE/IT
273/338
malloc (contd.)
More E.gs:
double *x;
x = (double *) malloc (100 * sizeof (double));
This is the correct declaration, gives us 800 bytes
in memory, where we have 100 doubles.
Always better to use sizeof instead of the
following:
x = (double *)malloc (100 * 8); // assume that double is
8 bytes
CSE/IT
274/338
Dynamic Memory
Other memory allocation functions:
void *calloc (size_t count, size_t size)
Same as malloc, but is contained in stdlib.h
Allocated space is automatically initialized to
zero.
Still have to cast void pointer to correct type.
CSE/IT
275/338
Allocating multiple
blocks of memory :calloc
Advantages over malloc:
Allocated memory is automatically initialized.
The semantics of size and count are separated,
making it easier for the user during declaration.
Less prone to making errors while declaration
for the correct amount of size and/or count
required.
CSE/IT
276/338
calloc (contd.)
E.g:
int *x;
x = (int *) calloc (10, sizeof (int));
Gives us a block of 10 integers in memory.
char *x;
x = (char *) calloc (10, sizeof (char));
Gives us a block of 10 characters in memory.
CSE/IT
277/338
278/338
Dynamic Memory
More functions:
void *realloc (void *blk, size_t newsize)
blk is pointer to previously allocated block of
memory using either malloc or calloc.
Attempts to reallocate the block of memory.
Resizes the memory to newsize (can be greater or
smaller than previously designated size).
CSE/IT
279/338
CSE/IT
280/338
realloc (contd.)
Pit falls:
size = 0 frees memory block and returns NULL.
Once memory is re-allocated, the old location in
memory is invalid.
Both memory locations (new and old), are the
same now (= new).
Example follows.
CSE/IT
281/338
realloc (contd.)
E.g:
# include <stdio.h>
int main ()
{
int *x, *y;
x = (int *) malloc (1 * sizeof (int));
*x = 1; // value of *x is 1 here.
y = (int *) realloc (x, 1);
*y = 10; // value of *x and *y are same = 10 !!!
printf ("%d\n", *y);
printf ("%d\n", *x);
}
CSE/IT
282/338
realloc (contd.)
malloc
realloc
realloc
y
malloc
CSE/IT
283/338
Dynamic Memory
Memory that is allocated can also be freed to the
heap.
Only dynamically allocated memory can be freed.
E.g:
int x; // memory for x is statically assigned here,
hence it cannot be freed.
CSE/IT
284/338
Dynamic Memory
(contd.)
When finished using dynamically allocated memory,
free it.
Good practice to avoid memory leaks.
Growing loss of memory due to unreleased
locations.
Could prevent program from running properly,
due to lack of memory.
Can run out of memory.
CSE/IT
285/338
Dynamic Memory
(contd.)
Function to free memory:
void free (void *blk)
De-allocates memory block previously allocated
with malloc, calloc or realloc.
blk is pointer to existing memory block already
allocated.
CSE/IT
286/338
CSE/IT
287/338
free
No return value.
Available in the header file stdlib.h
Never free a memory block that is not dynamically
allocated.
E.g:
int *x;
free (x); // error
CSE/IT
288/338
free (contd.)
Once block has been freed, do not attempt to access
it.
E.g:
char *x;
x = (char *) malloc (10 * sizeof (char));
free (x);
strcpy (x, welcome); // error as memory has
already been freed.
CSE/IT
289/338
free (contd.)
Free memory only when you are sure of not using it
again elsewhere in the program.
Cannot free memory already freed.
E.g:
char *x = (char *) malloc (10 * sizeof (char));
free (x);
free (x); // ERROR
CSE/IT
290/338
Pit falls
Memory is being manipulated directly, so any error
will stop your program.
Free memory at the end of the program.
Use realloc as little as possible.
As once realloc is executed, new location and
old location map to the same address in memory
char *x = (char *) malloc (10 * sizeof (char));
char *y = realloc (x, 15);
free (x); // y is also freed as x y.
CSE/IT
291/338
Pit falls
Dangling pointer:
E.g:
char *x, *y;
x = (char *) malloc (10 * sizeof (int));
y = (char *) malloc (10 * sizeof (int));
x = y; // cannot access what was in x anymore, so that block
is always lying around in memory with no way to free it
until program terminates.
CSE/IT
292/338
Files in C
A file must first be opened properly before it can be
accessed for reading or writing. When a file is
opened, a pointer is associated with the file.
Successfully opening a file returns a pointer to (i.e.,
the address of) a file structure, which contains a file
descriptor and a file control block.
CSE/IT
293/338
Why files?
Scanf and Printf are the built-in files used for
console-oriented operations i.e., giving I/P from
keyboard and getting O/P on the screen.
Files are used to store data in a manner that can later
be retrieved and displayed especially in large
volumes.
Files are used to store the information permanently
and to access information whenever necessary.
Files are stored in the Secondary Storage Devices like
Floppy Disks, Hard Disks.
CSE/IT
294/338
Data Organization
Memory
Our
Program
C Library
Functions
OS
Input and
DISK
Output
for File
Oriented
Operation
s For large
volumes of data
CSE/IT
295/338
Types of Files
Text File
Binary File
CSE/IT
296/338
Text File
Stores textual information like alphabets, numbers,
special symbols .etc.,
Ex: A-Z, a-z, 1,2,3etc., : , ; , , , ? etc.
Represented as C source code files with .txt
extension.
Text File operations include the above mentioned
six operations which are performed with the help of
C built-in functions.
CSE/IT
297/338
Binary File
Any files which store the data in the form of bytes
is a binary file.
Every executable file generated by the C compiler is
a binary file.
Ex: .exe files, video stream files, image files
etc.
Reading from a file, Writing to a file, Appending
files etc are also a part of binary file operations
done with the help of built-in functions.
CSE/IT
298/338
File Operations
1.
2.
3.
4.
5.
6.
CSE/IT
299/338
300/338
301/338
Examples:
FILE *fp1,*fp2;
fp1=fopen(data,r);
fp2=fopen(results,w);
File data is opened for reading only.
File results are opened for writing only.
r+, w+, a+ are also included in the latest compilers.
CSE/IT
302/338
List of Functions
Functions
Operation
fopen()
fclose()
fgetc()
fputc()
fprintf()
303/338
List of Functions
(Continued..)
Functions
Operation
fscanf()
fgetw()
fputw()
fseek()
CSE/IT
304/338
305/338
Closing a file
Prevents accidental misuse of the file.
fclose (file_pointer);
Ex:
FILE *fp1;
.
fclose (fp1);
CSE/IT
306/338
Input/output operations
on files
getc and putc functions
getw and putw functions
printf and fscanf functions
CSE/IT
307/338
308/338
Program
Read data from keyboard, write it to a file called
INPUT, again read the same data from the INPUT
file and display it on the screen.
CODE:
main ()
{
FILE *fp1;
char c;
printf("Data Input\n\n");
fp1 = fopen("INPUT","w");
CSE/IT
309/338
Continue..
while((c=getchar())!=EOF)
putc(c,fp1);
fclose(fp1);
printf("\nData Output\n\n");
fp1=fopen("INPUT","r");
while((c=getc(fp1)) !=EOF)
printf("%c",c);
fclose(fp1);
system("PAUSE");
}
CSE/IT
310/338
CSE/IT
311/338
Program
Read integers from keyboard and write the same
into file data and display the same on keyboard.
Code:
main ()
{
FILE *fp1;
int i,num;
printf("Contents of data file\n\n");
fp1 = fopen("data","w");
CSE/IT
312/338
Continue..
for(i=0;i<=20;i++)
{
scanf("%d",&num);
putw(num,fp1);
}
fclose(fp1);
fp1 = fopen("data","r");
while((num=getw(fp1))!=EOF)
printf("\n%d",num);
fclose(fp1);
system("PAUSE");
}
CSE/IT
313/338
CSE/IT
314/338
Input/output operations
on files
fscanf :
Reads items in the list from the file with pointer fp.
Returns the number of items that are successfully read.
When the end of file is reached, it returns the value EOF.
fscanf(fp, control string, list);
Ex: fscanf(fp2, %s %d, item, &quantity);
CSE/IT
315/338
316/338
317/338
CSE/IT
318/338
feof function
Can be used to test for an end of file condition.
Takes file pointer as its only argument
Returns a nonzero integer value if all of the data from
the specified file has been read.
Returns zero otherwise.
CSE/IT
319/338
feof function
if(feof(fp))
printf(End of data.\n);
Would display the message on reaching the end of file
condition (File opened for reading).
CSE/IT
320/338
ferror function
Reports the status of the file indicated.
Takes file pointer as its argument.
Returns non zero integer if an error has been
detected up to that point, during processing.
Otherwise returns zero.
CSE/IT
321/338
ferror function
if(ferror(fp) !=0)
printf(An error has occured.\n);
Would display the error message if reading is not
successful.
CSE/IT
322/338
Program
Program to illustrate error handling functions:
Code:
main()
{
char *filename;
FILE *fp1,*fp2;
int i,num;
fp1 = fopen("TEST","w");
for(i=0;i<=100;i+=10)
putw(i,fp1);
fclose(fp1);
CSE/IT
323/338
Continue..
fp1 = fopen("TEST","r");
for(i=1;i<=10;i++){
num=getw(fp1);
if(feof(fp1)) {
printf("\nRan out of data.\n");
break; }
else
printf("%d\n",num);
}
fclose(fp1);
system(PAUSE);
}
CSE/IT
324/338
CSE/IT
325/338
CSE/IT
326/338
CSE/IT
327/338
328/338
329/338
Meaning
Beginning of file
Current position
End of file
Offset:
positive -> meaning move forwards
negative -> meaning move backwards
CSE/IT
330/338
Statements and
Meanings
Statement
Meaning
fseek(fp,0L,0)
fseek(fp,0L,1)
fseek(fp,0L,2)
fseek(fp,m,0)
fseek(fp,m,1)
Go to forward by m bytes.
fseek(fp,-m,1)
331/338
CSE/IT
332/338
Program
Program that uses functions ftell and fseek:
Code:
main()
{
FILE *fp;
long int n;
char c;
fp=fopen("Random","w");
while((c=getchar())!=EOF)
putc(c,fp);
CSE/IT
333/338
Continue..
printf("No. of characters entered = %ld\n",ftell(fp));
fclose(fp);
fopen("Random","r");
n=0L;
while(feof(fp)==0){
fseek(fp,n,0); //position to (n+1)th character
printf("Position of %c is %ld\n", getc(fp),ftell(fp));
n++;}
fclose(fp);
system("PAUSE");
}
CSE/IT
334/338
Command line
arguments
It is a parameter supplied to a program when the
program is invoked.
Parameter may represent a file name the program should
process.
Command line to copy contents of a file named X_FILE
to another one named Y_FILE:
C > PROGRAM
PROGRAM is the file name where the executable code
X_FILE Y_FILE
of the program is stored.
CSE/IT
335/338
Command line
arguments
main function:
can also take arguments like other functions.
Can take two arguments called argc and argv.
The information contained in the command line is
passed on to the program through these arguments,
when main is called up by the system.
CSE/IT
336/338
Command line
arguments
agrc:
Is an argument counter
counts the no. of arguments on the command line.
argv:
Is an argument vector
Represents an array of character pointers that
points to the command line arguments.
Size of this array = value of argc.
CSE/IT
337/338
Command line
arguments
Ex:
C > PROGRAM X_FILE Y_FILE
Here,
argc = 3
argv = array of three pointers to strings,
argv[0] = PROGRAM
argv[1] = X_FILE
argv[2] = Y_FILE
CSE/IT
338/338
Command line
arguments
To access these command line arguments, we must declare
the main function and its parameters as:
main (int argc, char *argv[])
{
.
.
339/338