WHAT ISA UNION?
“Tie CO) day O- VOy @ ml
\2-Cison is user defined datatype (very simlar to structures)
Urine ference benween structures and unions lis the fact that in structure, each member has its own
storage location, whereas members of a union uses a single shared memory location. a raat
5 2 ge red manor leton ea vd sae of largest da member,
ay Aah be ployee i + Bed Be Lo
ce rgb 7a | fink wei
& ce age? = vd romeo" aeDECLARING AND ACCESSING UNION MEMBE!
(2 Ghee seructures, we access any member by using the member access operator (.)n unions
-_ «
L
6 bod, J Wet Ste rman
=_ieuse keyword union to define a union.&STATIC VARIABLES IN CLOCAL VARIABLES (RECAP)
2 Scope is region of the program where a defined variable can exist and beyond which it cannot be accessed
_2-Griables which are accessed inside a function or a block are called local variables.
2 They can only be accessed bythe function they are declared
<3-They are inaccessible to the functions outside the function they are declared in! -
oun) 2 fame vk a
ink ink ey 4
ink ests Gi
whoo 475GLOBAL VARIABLES (RECAP)
2 These are the variables defined outside the main method.
\_2--Gobal variables are accessible throughout the entire program from any function,
(f+ local and global varable has the same name, the lea variable wil take preference
int 415,
aie 3s int Sued 2
int mam) § fink 2 35
11 Soescole prot ("4 5
aehunds z
3FORMAL ARGUMENT:
#_Aifese variables are treated as local variables with
in a function.
# These variables take precedence over global
variables.STATIC VARIABLES IN C
\_2-They preserve their value from the previous scope and are not initialized again.
\_2-Stfic variable remains in memory throughout the span of the program.
_2-SGitic variables are initialized to 0 if not initialized explicitly
<2, static variables can only be inialized using constant eraOy
PDYNAMIC MEMORY ALLOCATION IN GWHAT & WHY DYNAMIC MEMORY ALLOCATION?
. s$ \o
char name [34] 5 hubba \o
Arana
—
E-AiTTatically allocated variable or array has a fixed size in memory. Shyam \o —___
it have learnt to create big enough arrays to fit in our inputs but this doesn’ seem lke an optimal way to
allocate memory.
te Hremory is a very useful resource
__2-CTearly we need a way to request memory on runtime
+
1 _Dumatinic Memory Allocation is way in which the size ofa data structure can be changed during the
Funtime.STATIC VS DYNAMIC MEMORY ALLOCATION
ink ¥>
Static Memory Allocation J — Dynamic Memory Allocation ~~
= Allocation is done before the = Allocation is done during the
program's execution | — program's execution -—~
= There is no memory reusability = There is memory reusability and
and the memory allocated cannot the allocated memory can be
be freed. Va freed when not required ~ -—
= Less efficient ~— = More efficient ~~MEMORY ALLOCATION IN C PROGRAMS
Quik 7
* Memory assigned to a program in a typical architecture can be broken down into four segments:
Ao Code ——> Tent eg
So nnn a sgn
Te Sack Fs seg ( unimregel
Zempiter allocates some space for the stack part Ce
Bo
of the memory
[--When this space gets exhausted for some bad g
reason, the situation is called as stack overflow
| +Afpical example includes recursion with wrong/no
base condition.C PROGRAM: USE OF HEAP
[- Are are a lot of limitations of stack (static
memory allocation)
+_Aéme of the examples include variable sized array,
freeing memory no longer required etc.
| Heap can be used flexibly by the programmer as
‘4 per his needs. =C PROGRAM: USE OF HEAP
C
int
2M can create a pointer in our main function and
point to a memory block in the heap
<|eThe address is stored by the local variable in the
main function,
[Te memory consumed will not get freed
automatically in case we overwrite the pointerFUNCTIONS FOR DYNAMIC MEMORY ALLOCATION
—>_InpseDYNAMIC MEMORY ALLOCATION: RECAP
(LAFF szatically allocated variable or array has a fixed size in memory.
f_Dimamic Memory Allocation isa way in which the sie of a data structure
‘ean be changed during the runtime
_Liemony assigned to a program ina typical architecture can be broken dawn into
four segment
. _
Code . int ore Lo]; —
—
Seack
ued
Statie/global variables = 3)
3 io]
HeapFUNCTIONS FOR DYNAMIC MEMORY CATION IN C
(OT Dynamic memory allocation, the memory is allocated at runtime from the heap segment
* We have four functions that help us achieve this task:
rao
Cp aloe = Dynan mamory ley
Ub raalloc
Ue beeC MALLOC()
n
int” pes .
we J! 2¥> mam
\_2-They are same as global variables
(U2-Beope: Global to the program they are defined in
(f-Pefaule initial Value: 0
UJ itotime: These variables are deciared outside any function. They are avaiable throughout the Mfetime of the
program
2K tlobal variable canbe changed by any function inthe program.
_Z-int hamry written outside any function will ell compiler that harry is a global variable.
> #8 recommended to minimize the use of unnecessary global variables ina program.EXTERNAL VARIABLES: EXTERN VARIABI
‘extern keyword is used to inform our C compiler that a given variable is declared somewhere else.
Ising extern will not allocate space for the variable definition
= Brample Acclarvhon fad
ory C = Mare +c
int main()
{
int harry = 90;
prinei("%d", harry);IC VARIABLES: STATIC STORAGE CLASS
fume tOS4
[giahe int «=85
(pBeope: Local to the block they are defined in
7 Befaute Initial Value: 0
Lifetime: They are available throughout the lifetime of the program.
LZ Aisa variable remains under existence for use within the function for entire program run
T-Taatic int harry written inside any function wil tell compiler that harry isa static variable.
ee recommended to minimize the use of unnecessary static variables in a program. aREGISTER VARIABLES: REGISTER STORAGE CLASS
\c pu Reqiskr
func xd,
{27Scope: Local to the function they are declared in
2 Default Initial Value: Garbage value
_ZAifetime: They are available til the end of the function block, in which the variable is defined
2A variables requests the compiler to store the variable inthe CPU register instead of storing in the
‘memory to have faster access abel
2 Fenlly this is done for the variables which are being used frequentlyore cane ry
om
Se Ce rrCoat
roy*
oy
r
(em)
oVOID POINTER IN C |WHAT IS AVOID POINTER?
{2-7 Fold pert ple hat hat po data ype assocaned wth THE
5A void pointer can be easily typecasted to any pointer type
© In simple language it is 2 “4 purpose pointer variable
Void fuel
farel (D4 e -] | PROGRAMMING
pet ~\s LANGUAGE
io]VOID POINTER: C PROGRAM
2K void pointer is a pointer that has no data type associated with it.
Ftd pana an bu ely pecan tle Pcl .
as ai! THE
To]
int x = 10; 7
char y = 'x'; —B [8
°
_/ void *p = &; // void pointer stores address of int ‘x*
Wp = &y; // void pointer now holds address of char ‘y"
PROGRAMMING
LANGUAGEUSES OF VOID POINTERS
THE
\2ATaynamic memory allocation, malloc() and ond rants *) type pointer
Tris allows hese dynamic memory functions tobe used to allocate memory of
any datatype. This is because these pointers can be typecasted to any pointer typ
PROGRAMMING
LANGUAGEMORE ON VOID POINTERS
\oid- a a ml 34 ae
(+ pe) i THE
(27 Fis not possible to dereference void pointers
(UL Pointer arithmetic no allowed in C standards with void pointers
\e-Hice ic is not recommended to use pointer arithmetic with void pointers.
PROGRAMMING
LANGUAGESs
float b
void *ptr;
da b;
8 (onli
ptr = Sa;
i¢
CF}
a ey
a8
PA
PNY
((float *)ptr));
Cet ae] 1) DFWHAT ISA NULL POINTER?
*_DiatT pointer is a pointer which has a value reserved for indicating that the
pointer or reference does not refer to a vahd object THE
2K il poater is guranteed to compare unequal to any pointer that points toa
valid object.
Oy creche ing a null pointer is undefined behavior in C, and a conforming
implementation is allowed to assume that any pointer that is dereferenced is
not null
—+ poinkas PROGRAMMING
3 Void rindi, LANGUAGE
Null povidor fyWHAT IS A NULL POINTER?
oid NULL
2 -AGull poincer is a pointer which has a value reserved for indicating that the THE
pointer or reference does not refer to a valid object.
ud ull pointer is guaranteed to compare unequal to any pointer that points to a
Valid object.
(I PHULL pointer sa spect pointer whichis mentioned in € standard and it has
‘specific purposes.
LANL poreer gras trctoey 10 € programmes to check whether a pointer PROGRAMMING
—— LANGUAGELL POINTER: C PROGRAM
2A pointer sa pointer that points to NULL (nothing)
2 Friuil pointer should not be dereferenced THE
pt Rreck must be run by the c programmer to know whether a pointer is null before
dereferencing it ——
Cannot be deveferente
int x = 10; A .
int *p = NULL; // null pointer PROGRAMMING
p = &x; // null pointer now holds address of int ~ LANGUAGE
Cam be. darsferonced osMORE ON NULL POINTERS
nul
or prt rd .
[Par THE
implementations
LEANGLL pointer vs Uninitializ = pointer ~ An uninitialized pointer contains an
“undefined value.
{Ziti pointer stores a defined valve, which isthe one decided by the environment to
not be a valid memory address for any object.
CAL pointer vs Void Pointer — Null pointer is a value where as void pointer is a
ope aes PROGRAMM
mt” per LANGUAGE
*btr
WhO hot oe (GNirs (6)
int a = 34;
Tee tule
%d\n", ptr);ar O
int a = 34;
int * ptr = NULL;
( ber( Kd\n", *pte);Cire
( Seasint )
r
bad ey
nt © ptr;
Come nay
( Xd\n", ptr);
rSa TdWHAT ISA DANGLING POINTER?
Pointer pointing to a freed memory location or the location whose content
has been deleted is called a dangling pointer. THE
Daring pointers arise during object destruction when an object that has an
incoming reference is deleted or deallocated, without modifying the value of the
pointer, so that the pointer still e f0 the memory location of the deallocated
mano ink @ vw r
.- PROGRAMMING
Vert LANGUAGE
=CAUSES OF DANGLING POINTER
po TA
2 Cralocation of memory THE
2 -Rtturning local variables in function calls
. a Aiiable going out of scope
*
PROGRAMMING
LANGUAGE
io]| DEALLOCATION OF MEMORY
When memory is deallocated, the pointer keeps pointing to the freed space.
= Example:IS DANGLING POINTER A GOOD THING TO HAVE?
eo @r
LPGirg pointers can introduce nasty ug in our C programs.
2 Aiialing pointer bugs frequently become security holes at times
5G can avoid issues caused by dangling pointers by initializing pointer to NULL
FF dealocaing rere, pobeer il be wo looger dungingzg=)
THE
2 Assigning NULL value means pointer is a null poincer now
PROGRAMM
ptr = NUL; LANGUAGEVARIABLE GOING OUT OF SCOPEWHAT IS AWILD POINTER?
* *
wiles, ing” por 5 [wilde
trivialized pointers are known as wild pointers — THE
i Titese pointers point some abierary location in memory and may cause a .
‘program to crash or behave badly.
Links “rhe finctio
© fred mt Inploutlonse
© brn ~ ‘Sole ~*~
aioe
a rather toleWHAT IS A C PREPROCESSOR?
xy
{2 preprocessor comes under action before the actual compilation process 4 THE
EC preprocessor is not a part of the ¢ compiler a
(2 Wis a text substitution tool
UT preprocessor commands begin with a hash symbol (#)
Juda OK? Gene PROGRAMMING
Le mt LANGUAGE
wk By * rit
@ Jv y
+r"
a owPREPROCESSOR COMMANDS EXAMPLES
o
Wo
Vy
define N
tinelude we
#undef
det
Wort gt Fine Undid is hoe
Helse ~
tertd
In,
H
Wed
ACRTIMP
Pavee
ACRTIMP
on
yea!
(rr a a
Coyle
sa Cee ts eat
valid parameter_handler _cdecl _set
Come Cees
invalid_parameter_handler __cdecl _ge
POR am rot
SRC Cen een nti
opt_ _{nvalid_parameter_handler _Hand)Pog#INCLUDE & #DEFINE PREPROCESSORS IN CTHE # INCLUDE DIRECTIVE
= Aho #tinclude directive causes the preprocessor to fetch the contents of some other file to be included in the
present file
17 1E tu ey nar Schapira which rag in tare bo se.
(£1T cement te Heke es hve 3" extending ta they ae ear les
* —_
per My
\0 GilesTWO COMMON #INCLUDE FORMATS
At C programming there are two common formats for #includes:
# tinclude < headerFileh > // The angle brackets say to look in the standard system directories
© tinclude * myfile.h/ The quotation marks say to look in the current directory,
_3-Disk drive full path is allowed, but discouraged since it is not portable:
|2--#include /! Too specific | -—
2 tinclude <
Relative and porable path to the standard locations.
.E # DEFINE DIRECTIVE
Ddpe PEPE - eas
4 Ode T il es
(Ua The fidefine directive is used to “define” preprocessor “variables”
(27 The fdefine preprocessor directive can be used to globally replace a word with a number
2 Tipets as an editor did a global search-and-replace edit of the file
etniesUSING #DEFINE FOR DEBUGGING
gr bye DEG
uv G
arith DEBS
‘
<2 aetine directive can be used for debugging
2-We can have printing statements that we only want active when debugging
swe printing statements that ly want acti oak
(2A fe can “protect” them in a "def" block as follows ss
ae wo} DEYMACROS USING #DEFINE
2A can also create macros using define
[orcs operate much ike functions but becauze they are expanded in place and are general faster
4 doje PL 3l4
+ dsjine cavart (¢) xk]
.* SQvARE (wes)
to = ak
C sae? OM win
Ten ©oyfloat var = PIOTHER DIRECTIVES AND PREDEFINED MACROSPREPROCESSOR DIRECTIVES
\2-Preprocessor is a kind of automated editor that modifies a copy of the original source code
#_-Fite include directive causes the preprocessor to fetch the contents of some other file to be included in the
present file
LZ-HIC programming there are two common formats for #includes:
\L2—This file may in turn #include some other file(s) which may in turn do the same.
test commonly the included files have a "1h" extension, indicating that they are header fils
* Tha,jidefine directive is used to "define" preprocessor "variables"OTHER C PREPROCESSORS.
Si {Ae
Ft unde — Undafives @ macro
ve fd —>
# ifndal —>
aif
deo
+ lf >
H Pryna DB isee Some shecid Conmnads 40 she Couahibena=) NSP Cel Ot ROE cL
S.No.
ee
2
Macro & Description
DATE Jom 3 209
e current date as character literal in "MMM DD YYYY™ format.
TIME
This contains the current time as a character literal in "HH:MM:SS" format.
FILE
The current filename as a string literal
_LINE_
The current line number as a decimal constant.
sTDC
Defined as (one) when the compiler complies with the ANSI standard.( %d\n", __LINE__);
( %d\n", __STOC__);FILE VO INC |WHY DOWE NEED A FILE?
les are used to read & access data anytime from the hard disk
Ee" used to store data and information
(2 iles make it easy for a programmer to access and store content without losing it on program temination
xyVOLATILE VS NON VOLATILE MEMORY
wats DSK
Volatile Memory --~ RW, Non Volatile Memory
+ 6tuile memory is computer storage that only 1 Gn-volatile memory is computer memory that can
maintains its data while the device is powered retain the stored information even when not
‘The RAM will hold data, programs, and information Powered,
as long as it has a constant power supply but tPrt pe of memory i aso refered to a
immediately the power is interrupted all that permanent memory since data stored within it can
content is cleared. be retrieved even when there is no constant power
ee vere
pM memory ln ld aa temporal
UA ised forthe long-term storage of data.WHY DO WE NEED FILES?
7 Rondon .
teen nena
_2AGringin a fle will preverve our data even after the program terminates
2AM is notable to handle quite large amount of data due to its smal size relative to the hard disk
pA cay ants éta2 eWHY DO WE NEED FILES?
RAM = g. don ACCESS Memory
po Crees nope oe es odie oa bm
_2A2Gringin a fle wil preverve our data even after the program terminates
_2-RAM isnot able to handle quite large amount of data due to its small size relative to the hard disk.
GAC cay antralTYPES OF FILES
Sem Plow et
\
os2-1" C we can perform these high level operations on files: a = |
_S—Creaung new fle
3 Opening 2 fle
—_——>
(Jo Closing a fe —FILE I/O FUNCTIONS IN C |WORKING WITH FILES IN C
Le fl
2 fen working with files, we have to declare a pointer of type FILE. sls) RAM *
\t_Drteclaration helps us to work with files through C program.
FILE * per= NvllsOPENING A FILE — CREATING OR EDITING A FILE
dak tb
a function called & Te
pening 2 fei 400 is fileCLOSING A FILE
—. open ( ‘
+ Ae eich is opened in 2C program neds to be closed
=, Closing file accomplished by the library function
°
* felosefper: per isthe fle pointer associated with file to beREADING A FILE
tr,
2A rder to read a file, we can use fscanf function Asian Cr —
ts function is file version of scanf function
“eAeant expects 2 file pointer in addition tothe other arguments which scanf expects
= Wewill have to open the file in read mode in order to use this function
*WRITING TOA FILE
Sim print
int ps’
pen vintf( per "Ss
(2 order to write to fle, we can use fprintf function, 4p ( orig) ;
LEAT function is file version of printf funetion
(2 frtintt expects a file pointer in a
27% wt ave to open she fe fodelin order to use this function
*
to the other arguments which printf expectsthis is some content in this file
A this is a good file
3 this file is by harryod nt oO
3 ee aie
i es U ess
a ( 5 5
ope certs oe
r Po Ceemain()
ie er ae
esr) coal
ra
fprintf(ptr, "
UC ee ee ee et TCL
fopen(“myfile.txt", “w");
Presto
Pe emt
oo
Perr a)
aThis content was produced by Tutorial64.¢ro r a oy)
Hire Ree E SFee Ce re a Cy CaM eee ee ery
eee Mae ee eM aR co eC)MORE ONIFILE I/O IN C}WORKING WITH FILES IN C
Coo) _Fofem (“man kat", "ve
# stdioh contains a function called fopen() for opening files in C a
* When working with files, we have to declare a pointer of type FILE FILE * pes
* This declaration helps us to work with files through C program.
® The syntax for opening a file in standard V/O is: ptr
+ (emecteager ese
trond to rendre to le. we an use ani fneion
© icant "Ks" bully printer, "Marks= "salary
cSoniggs ‘ptr is the file pointer associated with file to be closedMODE & DESCRIPTION
cro
CS ‘Opens an existing text file for reading
wor ‘Opens a fle for writing. If it doesnt exist then a new file is
created. Writing starts from the beginning ofthe file.
as ‘Opens a text fle for writing in appending mode. If it does not
‘exist then a new fle i created. The program wil stat appepding
content to the existing file content.
ne ‘This mode will open a text file for both reading and writing
we ‘Opens a text fle for both reading and writing fe frst truncates,
the file to zero length iit exists, otherwise creates afl fit ~
does not exist.
a ‘Opens a text fle for both reading and writin, It creates the fle
. if it does not exist. The reading wil start from the beginning but
‘writing can only append to file.pe He
2-Sfplest function to wrive characters to 3 file is fue
2 Afitax of fpute goes as follows:
nt fpute( character. FILE pointer ): =
‘Ie returns the written character written on success,
© On faire t recurns EOF
= The EOF isa constant defined in the header file stdio.hOTHER FILE I/O FUNCTIONS IN C
a
vere are various functions provided by C standard library to read and write a file, character by character, or in
the form of a fixed length string
Some of them are:
fpute
Spurs
fgete
= fersthe rele
a Choy")de
L2-Simplest function to write characters to a file is fpute
2 Afitax of fpute goes as follows:
tnt fpute( character, FILE potter Jee
Ie returns the written character written on success. ~~
© On faire ie reruns EOF
+ The EOF isa constant defined in the header file stdio-hFGETC FUNCTION IN C
® Simplest function to read characters from a file is fgete
= Syntax of fgete goes as follows:
© tnt fgete( FILE "fp )
Ie returns the read character on success.
© On failure t pews EOF
The EOF isa constant defined in the header file stdio.h,ut
harry
= Syntax of fgete goes as follows:
Fe geet FILE" fp)
Gn failure ic recurns EOF
The EOF isa constant defined in the header file stdio.h,
.ate fh
ts function is used to write a null terminated string to a file in ¢
tn fgets( const char *s, FILE “fp )ts function is used to eek null terminated string to a file in ¢
© st tgetst const cha 26 5EM pI
E wnt fyi (Lor dan’, ink,
FILe “tpQO
a oe
Peet re Oe Pe
Cn aot
pee ea ee ke Le
Pee eethis is goodi
ee ome ed
= ptr ( 1 5
hal oy
( % oy}
ce corea bi » str);or O
ron ee (char [2})*w
a i » “W")5OC er aca
i ptr);
rae)[3 er en
ptr ¢AE
wer
oFDe ee ee ce eee ence eet near nceeee nen rceet eenCOMMAND LINE ARGUMENT IN CMiele OO) Miley PHAN ASE E NUS)
fnmand line argument is an important concept in C programming
netimes we need to pass arguments from the command line to the program a set of inputs.
TGmmand line arguments are used to supply parameters to the program when itis invoked
we mostly used when you need to control your program from the console
(LAG & ments are passed to the main) method
= men TER melt
4
ee,COMMAND LINE EXAMPLE
oe
# EF mpeg is a free and open-source project consisting of a vast software suite of libraries and programs for handling
video, audio, and other multimedia files and streams.
5_-Fimpeg.exe is a command line utility written in ¢ language.
ine examples include git, brew, apt-get ete.
f
b a Vet ope
qe » =SAMPLE PROGRAI "|ys (int Pao )
( PL <<Tae ca ee ee
Tet @a RTC ae iy aed
for (int i=@5 ic arge; iv+){
print€("This argument at index number Xd has a value of %:
cop
» argc);
Sead|
|FUNCTION POINTERS IN CPOINTERS
Pears er j
_ CR
(L2-A Pointer isa variable which stores address of another variable
2B symbol is used to get the address ofthe variable
(27 srmbol is used to get the value of the variable thatthe pointer is pointing ta.
ZAC. we can create generic pointers to0
% Sepiar C varlable stores the value whereas pointer stores the ares ofthe vara.
uwFUNCTION POINTERS
Hwa Hbygeer
2 an re ptr pon nen wll Ass: Twn il
\(e-#tction pointers are useful to implement callback functions
LL Seroiter takes one or more source files and converts them to machine code
eds dafrten
peo [imi
aD
De IT43
ue‘
)
>
i
PCED}_
[USING FUNCTION POINTERS IN CFUNCTION POINTERS
(2PM can have pointers pointing to functions as well
Pr Fiinction pointers point to code and not data
<3Finetion pointers are useful to implement callback functions
=_Untlike normal pointers, we do not alloate/de-allocate memory using function
pointers.
CaCALLBACK FUNCTIONS
Teal
_2-Pinction pointers are used to pass a function to a
functon foc ¢
Oe passed function can then be called again (hence the
name callback function).
his provides programmer to write less code to do more
stuff. Fe \ &
alway 7 3
—— — ! ba
‘ ast “ ea
=|MEMORY LEAK IN C |Niel 0),0 a aoa Bord
mamic Memory Allocation is a way in which the size of a data structure
an be changed during the runtime,
= Memory assigned to a program in a typical architecture can be broken down into
four segments: —
Code
2 Staticglobal variables
Or Sack
i time let
wenWHAT CAUSES MEMORY LEAK IN C?
2A grese power comes great esponsbilty
e--rremory leaks caused when we dont use namic memory properly
Lb *ifien we keep on allocating memory in the heap without freeing, the overall
memory usage keeps on increasing,
This situation is the cause of memory leak ie the programmer creates a
memory block in the memory and forgets to delete it.
= To avoid these memory leak situations, memory allocated on heap should
dha eae when to eed
. veea on