SlideShare a Scribd company logo
Team Emertxe
C
Come let's see how deep it is!!
Day 1
Introduction
C
Have you ever pondered how
- powerful it is?
- efficient it is?
- flexible it is?
- deep you can explore your system?
C
Brief History
●
Prior to C, most of the computer languages (such as
Algol)
– Academic oriented, unrealistic and were generally defined by
committees.
– Designed having application domain in mind (Non portable)
●
It has lineage starting from CPL
– Martin Richards implemented BCPL
– Ken Thompson further refined BCPL to a language named as B
– Dennis M. Ritchie added types to B and created a language C
●
With just 32 keywords, C established itself in a very wide
base of applications.
C
Where is it used?
●
System Software Development
●
Embedded Software Development
●
OS Kernel Development
●
Firmware, Middle-ware and Driver Development
●
File System Development
And many more!!
C
Important Characteristics
●
Considered as a middle level language
●
Can be considered as a pragmatic language.
●
It is indented to be used by advanced programmers, for
serious use, and not for novices and thus qualify less as
an academic language for learning
●
Gives importance to curt code.
●
It is widely available in various platforms from
mainframes to palmtops and is known for its wide
availability
C
Important Characteristics
●
It is a general-purpose language, even though it is applied
and used effectively in various specific domains
●
It is a free-formatted language (and not a strongly-typed
language)
●
Efficiency and portability are the important
considerations
●
Library facilities play an important role
C
Standard
●
“The C programming language” book served as a
primary reference for C programmers and
implementers alike for nearly a decade
●
However it didn’t define C perfectly and there
were many ambiguous parts in the language
●
As far as the library was concerned, only the C
implementation in UNIX was close to the
’standard’
●
So many dialects existed for C and it was the time the language has
to be standardized and it was done in 1989 with ANSI C standard
●
Nearly after a decade another standard, C9X, for C is available that
provides many significant improvements over the previous 1989
ANSI C standard
C
Keywords
●
In programming, a keyword is a word that is reserved by a
program because the word has a special meaning
●
Keywords can be commands or parameters
●
Every programming language has a set of keywords that
cannot be used as variable names
●
Keywords are sometimes called reserved names
C
Keywords - Categories
Type Keyword
Data Types char
int
float
double
Modifiers signed
unsigned
short
long
Qualifiers const
volatile
Loops for
while
do
Jump goto
break
continue
Type Keyword
Decision if
else
switch
case
default
Storage Class auto
register
static
extern
Derived struct
unions
User defined enums
typedefs
Others void
return
sizeof
C
Typical C Code Contents
Documentation
Preprocessor Statements
Global Declaration
The Main Code:
--------------------
Local Declarations
Program Statements
Function Calls
One or many Function(s):
---------------------------------
The function body
●
A typical code might contain the
blocks shown on left side
●
It is generally recommended to
practice writing codes with all
the blocks
C
Anatomy of a Simple C Code
/* My first C code */
#include <stdio.h>
int main()
{
/* To display Hello world */
printf("Hello worldn");
return 0;
}
File Header
Preprocessor Directive
The start of program
Comment
Statement
Program Termination
C
Compilation
●
Assuming your code is ready, use the following commands
to compile the code
●
On command prompt, type
$ gcc <file_name>.c
●
This will generate a executable named a.out
●
But it is recommended that you follow proper conversion
even while generating your code, so you could use
$ gcc <file_name>.c -o <file_name>
●
This will generate a executable named <file_name>
C
Execution
●
To execute your code you shall try
$ ./a.out
●
If you have named you output file as your <file_name>
then
$ ./<file_name>
●
This should the expected result on your system
Data Representations
Embedded C
Number Systems
●
A number is generally
represented as
– Decimal
– Octal
– Hexadecimal
– Binary
Dec
0 0 0 0
Oct Hex Bin
0 0 0 0
10 8 16 2
Type
Base
0 0 0
0 0 0 00 0 0 11 1 1
0 0 0 00 0 1 02 2 2
0 0 0 00 0 1 13 3 3
0 0 0 00 1 0 04 4 4
0 0 0 00 1 0 15 5 5
0 0 0 00 1 1 06 6 6
0 0 0 00 1 1 17 7 7
0 0 0 01 0 0 08 10 8
0 0 0 01 0 0 19 11 9
0 0 0 01 0 1 010 12 A
0 0 0 01 0 1 111 13 B
0 0 0 01 1 0 012 14 C
0 0 0 01 1 0 113 15 D
0 0 0 01 1 1 014 16 E
0 0 0 01 1 1 115 17 F
Decimal
Type Range (8 Bits)
Octal
Hexadecimal
Binary 0b00000000 - 0b11111111
0 - 255
000 - 0377
0x00 - 0xFF
Embedded C
Data Representation - Bit
●
Literally computer understand only two states HIGH and
LOW making it a binary system
●
These states are coded as 1 or 0 called binary digits
●
“Binary Digit” gave birth to the word “Bit”
●
Bit is known a basic unit of information in computer and
digital communication
0
Value No of Bits
0
1 1
Embedded C
Data Representation - Byte
●
A unit of digital information
●
Commonly consist of 8 bits
●
Considered smallest addressable unit of memory in
computer
0
Value No of Bits
0
1 0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
Embedded C
Data Representation - Character
●
One byte represents one unique character like 'A', 'b', '1',
'$' ...
●
Its possible to have 256 different combinations of 0s and
1s to form a individual character
●
There are different types of character code
representation like
– ASCII American Standard Code for Information→
Interchange – 7 Bits (Extended - 8 Bits)
– EBCDIC Extended BCD Interchange Code – 8 Bits→
– Unicode Universal Code - 16 Bits and more→
Embedded C
Data Representation - Character
●
ASCII is the oldest representation
●
Please try the following on command prompt to know the
available codes
$ man ascii
●
Can be represented by char datatype
0
Value No of Bits
A
0
0
0
1
1
0
1
0
0
0
0
0
0
0
0
1
Embedded C
Data Representation - Word
●
Amount of data that a machine can fetch and process at
one time
●
An integer number of bytes, for example, one, two, four,
or eight
●
General discussion on the bitness of the system is
references to the word size of a system, i.e., a 32 bit
chip has a 32 bit (4 Bytes) word size
0
Value No of Bits
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
Embedded C
Integer Number - Positive
●
Integers are like whole numbers, but allow negative
numbers and no fraction
● An example of 1310 in 32 bit system would be
Position
Bit No of Bits
Value
31
0
30
0
29
0
28
0
27
0
26
0
25
0
24
0
23
0
22
0
21
0
20
0
19
0
18
0
17
0
16
0
15
0
14
0
13
0
12
0
11
0
10
0
9
0
8
0
7
0
6
0
5
0
4
0
3
1
2
1
1
0
0
1
Embedded C
Integer Number - Negative
●
Negative Integers represented with the 2's complement of
the positive number
● An example of -1310 in 32 bit system would be
Position
Bit No of Bits
Value
31
0
30
0
29
0
28
0
27
0
26
0
25
0
24
0
23
0
22
0
21
0
20
0
19
0
18
0
17
0
16
0
15
0
14
0
13
0
12
0
11
0
10
0
9
0
8
0
7
0
6
0
5
0
4
0
3
1
2
1
1
0
0
1
1's Compli 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 0
Add 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
2's Compli 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1
●
Mathematically : -k 2≡
n
- k
●
Negative Integers represented with the 2's complement of
the positive number
● An example of -1310 in 32 bit system would be
Embedded C
Float Point Number
●
A formulaic representation which approximates a real
number
●
Computers are integer machines and are capable of
representing real numbers only by using complex codes
●
The most popular code for representing real numbers is
called the IEEE Floating-Point Standard
Sign Exponent Mantissa
Float (32 bits)
Single Precision
1 bit 8 bits 23 bits
Double (64 bits)
Double Precision
1 bit 11 bits 52 bits
Basic Data Types
Embedded C
Basic Data Types
Data
Types
Integral
Floating Point
char
int
float
double
Embedded C
Data Type Modifiers and Qualifiers
Modifiers
Size
Signedness
short
long long
signed
unsigned
long
T
T
T
T
T
Qualifiers
const
volatile
V
V
V Variables
T Data Types
F Functions
Notes:
- ANSI says, ensure that: char ≤ short ≤ int ≤ long
- unsigned float in not supported
Embedded C
Data Type and Function storage modification
Storage
Modifiers
auto
extern
register
inline
static
V
V
V
V
F
F
F
V Variables
T Data Types
F Functions
Conditional Constructs
Embedded C
Code Statements - Simple
int main()
{
number = 5;
3; +5;
sum = number + 5;
4 + 5;
;
}
Assignment statement
Valid statement, But smart compilers
might remove it
Assignment statement. Result of the
number + 5 will be assigned to sum
Valid statement, But smart compilers
might remove it
This valid too!!
Embedded C
Code Statements - Compound
int main()
{
...
if (num1 > num2)
{
if (num1 > num3)
{
printf(“Hello”);
}
else
{
printf(“World”);
}
}
...
}
If conditional statement
Nested if statement
Embedded C
Conditional Constructs
Conditional
Constructs
Multi iteration
Single iteration
for
do while
while
if and its family
switch case
Embedded C
Conditional Constructs - if
#include <stdio.h>
int main()
{
int num1 = 2;
if (num1 < 5)
{
printf(“num1 < 5n”);
}
printf(“num1 is %dn”, num1);
return 0;
}
ExampleSyntax
if (condition)
{
statement(s);
}
Flow
cond?
true
code
false
Embedded C
Conditional Constructs – if else
Syntax
if (condition)
{
statement(s);
}
else
{
statement(s);
}
Flow
cond?
true
code
false
code
Embedded C
Conditional Constructs – if else
#include <stdio.h>
int main()
{
int num1 = 10;
if (num1 < 5)
{
printf(“num1 < 5n”);
}
else
{
printf(“num1 > 5n”);
}
return 0;
}
Example
Embedded C
Conditional Constructs – if else if
Syntax
if (condition1)
{
statement(s);
}
else if (condition2)
{
statement(s);
}
else
{
statement(s);
}
Flow
cond1? code
true
false
cond2?
code
code
true
false
Embedded C
Conditional Constructs – if else if
#include <stdio.h>
int main()
{
int num1 = 10;
if (num1 < 5)
{
printf(“num1 < 5n”);
}
else if (num1 > 5)
{
printf(“num1 > 5n”);
}
else
{
printf(“num1 = 5n”);
}
return 0;
}
Example
Embedded C
Conditional Constructs – switch
Syntax
switch (expression)
{
case constant:
statement(s);
break;
case constant:
statement(s);
break;
case constant:
statement(s);
break;
default:
statement(s);
}
Flow
expr
code
true
false
case1? break
case2?
default
code break
code break
true
false
Embedded C
Conditional Constructs - switch
#include <stdio.h>
int main()
{
int option;
printf(“Enter the valuen”);
scanf(“%d”, &option);
switch (option)
{
case 10:
printf(“You entered 10n”);
break;
case 20:
printf(“You entered 20n”);
break;
default:
printf(“Try againn”);
}
return 0;
}
Example
Embedded C
Conditional Constructs – while
Syntax
while (condition)
{
statement(s);
}
Flow
false
true
cond?
code
#include <stdio.h>
int main()
{
int i;
i = 0;
while (i < 10)
{
printf(“Looped %d timesn”, i);
i++;
}
return 0;
}
Example
●
Controls the loop.
●
Evaluated before each
execution of loop body
Embedded C
Conditional Constructs – do while
Syntax
do
{
statement(s);
} while (condition);
Flow
false
true
cond?
code
#include <stdio.h>
int main()
{
int i;
i = 0;
do
{
printf(“Looped %d timesn”, i);
i++;
} while (i < 10);
return 0;
}
Example
●
Controls the loop.
●
Evaluated after each
execution of loop body
Embedded C
Conditional Constructs – for
Syntax
for (init; condition; post evaluation expr)
{
statement(s);
}
Flow
init
false
true
cond?
code
post eval
expr
#include <stdio.h>
int main()
{
int i;
for (i = 0; i < 10; i++)
{
printf(“Looped %d timesn”, i);
}
return 0;
}
Example
●
Controls the loop.
●
Evaluated before each
execution of loop body
Embedded C
Conditional Constructs – continue
Syntax
do
{
conditional statement
continue;
} while (condition);
Flow
●
A continue statement causes a jump
to the loop-continuation portion,
that is, to the end of the loop body
●
The execution of code appearing
after the continue will be skipped
●
Can be used in any type of multi
iteration loop
false
true
loop
cond?
code block
cond?
false
continue?
true
code block
Embedded C
Conditional Constructs – continue
#include <stdio.h>
int main()
{
int i;
for (i = 0; i < 10; i++)
{
if (i == 5)
{
continue;
}
printf(“%dn”, i);
}
return 0;
}
Example
Embedded C
Conditional Constructs – break
Syntax
do
{
conditional statement
break;
} while (condition);
Flow
●
A break statement shall appear
only in “switch body” or “loop
body”
●
“break” is used to exit the loop,
the statements appearing after
break in the loop will be skipped
false
true
loop
cond?
code block
cond?
false
break?
true
Embedded C
Conditional Constructs – break
#include <stdio.h>
int main()
{
int i;
for (i = 0; i < 10; i++)
{
if (i == 5)
{
break;
}
printf(“%dn”, i);
}
return 0;
}
Example
Embedded C
Conditional Constructs – break
#include <stdio.h>
int main()
{
int i;
for (i = 0; i < 10; i++)
{
if (i == 5)
{
break;
}
printf(“%dn”, i);
}
printf(“%dn”, i);
return 0;
}
Example
Operators
Embedded C
Operators
●
Symbols that instructs the compiler to perform specific
arithmetic or logical operation on operands
●
All C operators do 2 things
– Operates on its Operands
– Returns a value
Embedded C
Operators
Category
Operand
Operation
unary
ternary
Arithmetic
Logical
binary
+
!
Relational >
Assignment =
Bitwise &
Language sizeof()
Pointers *
- * / %
|| &&
< <= >= == !=
| ^ ~ >> <<
& ->
...
...
...
...
Embedded C
Operators – Precedence and Associativity
Operators Associativity Precedence
() [] -> . L - R HIGH
! ++ −− - + * & (type) sizeof∼ R - L
/ % * L - R
+ - L - R
<< >> L - R
< <= > >= L - R
== != L - R
& L - R
^ L - R
| L - R
&& L - R
|| L - R
?: R - L
= += -= *= /= %= &= ^= |= <<= >>= R - L
, L - R LOW
Note:
post ++ and –-
operators have
higher precedence
than pre ++ and –-
operators
(Rel-99 spec)
Embedded C
Operators - Arithmetic
#include <stdio.h>
int main()
{
int num1 = 0, num2 = 0;
printf(“sum is %dn”, num1++ + ++num2);
return 0;
}
Example
What will be
the output?
Operator Description Associativity
*
/
%
Multiplication
Division
Modulo
L to R
+
-
Addition
Subtraction
R to L
Embedded C
Type Conversion
Type
Conversion
Explicit
Implicit
Embedded C
Type Conversion Hierarchy
signed char
unsigned char
signed short
unsigned short
signed int
unsigned int
signed long
unsigned long
signed long long
unsigned long long
float
double
long double
Embedded C
Type Conversion - Implicit
●
Automatic Unary conversions
– The result of + and - are promoted to int if operands are
char and short
– The result of ~ and ! is integer
●
Automatic Binary conversions
– If one operand is of LOWER RANK (LR) data type & other is
of HIGHER RANK (HR) data type then LOWER RANK will be
converted to HIGHER RANK while evaluating the expression.
– Example: LR + HR LR converted to HR→
Embedded C
Type Conversion - Implicit
●
Type promotion
– LHS type is HR and RHS type is LR → int = char LR is promoted→
to HR while assigning
●
Type demotion
– LHS is LR and RHS is HR → int = float HR rank will be demoted→
to LR. Truncated
Embedded C
Type Conversion – Explicit (Type Casting)
#include <stdio.h>
int main()
{
int num1 = 5, num2 = 3;
float num3 = (float) num1 / num2;
printf(“num3 is %fn”, num3);
return 0;
}
Example
Syntax
(data type) expression
Embedded C
Operators - Logical
#include <stdio.h>
int main()
{
int num1 = 1, num2 = 0;
if (++num1 || num2++)
{
printf(“num1 is %d num2 is %dn”, num1, num2);
}
num1 = 1, num2 = 0;
if (num1++ && ++num2)
{
printf(“num1 is %d num2 is %dn”, num1, num2);
}
else
{
printf(“num1 is %d num2 is %dn”, num1, num2);
}
return 0;
}
Example
What will be
the output?
Operator Description Associativity
!
&&
||
Logical NOT
Logical AND
Logical OR
R to L
L to R
L to R
Embedded C
Operators - Relational
#include <stdio.h>
int main()
{
float num1 = 0.7;
if (num1 == 0.7)
{
printf(“Yes, it is equaln”);
}
else
{
printf(“No, it is not equaln”);
}
return 0;
}
Example
Operator Description Associativity
>
<
>=
<=
==
!=
Greater than
Lesser than
Greater than or equal
Lesser than or equal
Equal to
Not Equal to
L to R
What will be
the output?
Embedded C
Operators - Assignment
#include <stdio.h>
int main()
{
int num1 = 1, num2 = 1;
float num3 = 1.7, num4 = 1.5;
num1 += num2 += num3 += num4;
printf(“num1 is %dn”, num1);
return 0;
}
Example
#include <stdio.h>
int main()
{
float num1 = 1;
if (num1 = 1)
{
printf(“Yes, it is equal!!n”);
}
else
{
printf(“No, it is not equaln”);
}
return 0;
}
Example
Embedded C
Operators - Bitwise
●
Bitwise operators perform operations on bits
●
The operand type shall be integral
●
Return type is integral value
Embedded C
Operators - Bitwise
0x61
Value
0x13
0
0
1
0
1
0
0
1
0
0
0
0
0
1
1
1
00x60
Value
0x13
A
Operand
B
0x01 0 0 0 0 0 0 0 10x13A & B
& Bitwise AND
Bitwise ANDing of
all the bits in two
operands
0x61
Value
0x13
0
0
1
0
1
0
0
1
0
0
0
0
0
1
1
1
00x60
Value
0x13
A
Operand
B
0x73 0 1 1 1 0 0 1 10x13A | B
| Bitwise OR
Bitwise ORing of
all the bits in two
operands
0x61
Value
0x13
0
0
1
0
1
0
0
1
0
0
0
0
0
1
1
1
00x60
Value
0x13
A
Operand
B
0x72 0 1 1 1 0 0 1 00x13A ^ B
^ Bitwise XOR
Bitwise XORing of
all the bits in two
operands
Embedded C
Operators - Bitwise
0x61
Value
0 1 1 0 0 0 0 100x60
Value
A
Operand
0x9E 1 0 0 1 1 1 1 00x13~A
~ Compliment
Complimenting
all the bits of the
operand
0x61
Value
0 1 1 0 0 0 0 100x60
Value
A
Operand
0x18 0 0 0 1 1 0 0 00x13A >> 2
>> Right Shift
Shift all the bits
right n times by
introducing zeros
left
0x61
Value
0 1 1 0 0 0 0 100x60
Value
A
Operand
0x84 1 0 0 0 0 1 0 00x13A << 2
<< Left Shift
Shift all the bits
left n times by
introducing zeros
right
Embedded C
Operators – Bitwise – Left Shift
'Value' << 'Bits Count'
●
Value : Is shift operand on which bit shifting effect to be
applied
●
Bits count : By how many bit(s) the given “Value” to be shifted
0x61Original value
0x84
A << 2
Resultant value
0000110 1
0100001 0
Say A = 91
Zero filling left shift
Embedded C
Operators – Bitwise – Right Shift
'Value' >> 'Bits Count'
●
Value : Is shift operand on which bit shifting effect to be
applied
●
Bits count : By how many bit(s) the given “Value” to be shifted
Zero filling right shift
0x61Original value
0x18
A >> 2
Resultant value
0000110 1
0011000 0
Say A = 91
Embedded C
Operators – Bitwise – Right Shift – Signed Valued
“Signed Value' >> 'Bits Count'
●
Same operation as mentioned in previous slide.
●
But the sign bits gets propagated.
Zero filling right shiftSign bit filling right shift
0xA1Original value
0xE8
A >> 2
Resultant value
0000101 1
0010111 0
Say A = -95
Embedded C
Operators - Bitwise
#include <stdio.h>
int main()
{
int count;
unsigned char num = 0xFF;
for (count = 0; num != 0; num >>= 1)
{
if (num & 01)
{
count++;
}
}
printf(“count is %dn”, count);
return 0;
}
Example
Embedded C
Operators – Language - sizeof()
#include <stdio.h>
int main()
{
int num = 5;
printf(“%u:%u:%un”, sizeof(int), sizeof num, sizeof 5);
return 0;
}
Example
#include <stdio.h>
int main()
{
int num1 = 5;
int num2 = sizeof(++num1);
printf(“num1 is %d and num2 is %dn”, num1, num2);
return 0;
}
Example
Embedded C
Operators – Language - sizeof()
●
3 reasons for why sizeof is not a function
– Any type of operands,
– Type as an operand,
– No brackets needed across operands
Embedded C
Operators – Ternary
Syntax
Condition ? Expression 1 : Expression 2;
#include <stdio.h>
int main()
{
int num1 = 10;
int num2 = 20;
int num3;
if (num1 > num2)
{
num3 = num1;
}
else
{
num3 = num2;
}
printf(“%dn”, num3);
return 0;
}
Example
#include <stdio.h>
int main()
{
int num1 = 10;
int num2 = 20;
int num3;
num3 = num1 > num2 ? num1 : num2;
printf(“Greater num is %dn”, num3);
return 0;
}
Embedded C
Operators – Comma
●
The left operand of a comma operator is evaluated as a
void expression: Then the right operand is evaluated, the
result has its type and value
●
Comma acts as separator (not an operator) in following
cases
– Arguments to functions
– Lists of initializers (variable declarations)
●
But, can be used with parentheses as function arguments
such as -
– foo ((x = 2, x + 3)); // final value of argument is 5
Embedded C
Over and Underflow
●
8-bit Integral types can hold certain ranges of values
●
So what happens when we try to traverse this boundary?
Overflow
(127 + 1)
Underflow
(-128 - 1)
Embedded C
Overflow – Signed Numbers
0x7FOriginal value
0x80Resultant value
1111110 1
Say A = +127
1Add 0000000 1
0000001 0
Embedded C
Underflow – Signed Numbers
0x80Original value
0x7FResultant value
Say A = -128
-1Add
0000001 0
1111111 1
1111110 11
Array
Embedded C
Arrays – Know the Concept
Ends here
Starts here
A conveyor belt
Equally spaced
Defined length
Carry similar items
Index as 10th
item
Embedded C
Arrays – Know the Concept
Conveyor Belt
Top view First Element
Start (Base) address
Last Element
End address
●
Total Elements
●
Fixed size
●
Contiguous Address
●
Elements are
accessed by
indexing
●
Legal access region
An Array
Embedded C
Arrays
Syntax
data_type name[SIZE];
Where SIZE is number of elements
The size for the array would be SIZE * <size of data_type>
Example
int age[5] = {10, 20, 30, 40, 50};
10 20 30 40 50
Index 1
Index 2
Index 3
Index 4
Index 5
baseaddr
baseaddr+4
baseaddr+8
baseaddr+12
baseaddr+16
Embedded C
Arrays – Point to be noted
●
An array is a collection of data of same data type.
●
Addresses are sequential
●
First element with lowest address and the last element
with highest address
●
Indexing starts from 0 and should end at array SIZE – 1.
Example say array[5] will have to be indexed from 0 to 4
●
Any access beyond the boundaries would be illegal access
Example, You should not access array[-1] or array[SIZE]
Embedded C
Arrays – Why?
#include <stdio.h>
int main()
{
int num1 = 10;
int num2 = 20;
int num3 = 30;
int num4 = 40;
int num5 = 50;
printf(“%dn”, num1);
printf(“%dn”, num2);
printf(“%dn”, num3);
printf(“%dn”, num4);
printf(“%dn”, num5);
return 0;
}
Example
#include <stdio.h>
int main()
{
int num_array[5] = {10, 20, 30, 40, 50};
int index;
for (index = 0; index < 5; index++)
{
printf(“%dn”, num_array[index]);
}
return 0;
}
Embedded C
Arrays - Reading
#include <stdio.h>
int main()
{
int array[5] = {1, 2, 3, 4, 5};
int index;
index = 0;
do
{
printf(“Index %d has Element %dn”, index, array[index]);
index++;
} while (index < 5);
return 0;
}
Example
Embedded C
Arrays - Storing
#include <stdio.h>
int main()
{
int num_array[5];
int index;
for (index = 0; index < 5; index++)
{
scanf(“%d”, &num_array[index]);
}
return 0;
}
Example
Embedded C
Arrays - Initializing
#include <stdio.h>
int main()
{
int array1[5] = {1, 2, 3, 4, 5};
int array2[5] = {1, 2};
int array3[] = {1, 2};
int array4[]; /* Invalid */
printf(“%un”, sizeof(array1));
printf(“%un”, sizeof(array2));
printf(“%un”, sizeof(array3));
return 0;
}
Example
Embedded C
Arrays – Copying
●
Can we copy 2 arrays? If yes how?
#include <stdio.h>
int main()
{
int array_org[5] = {1, 2, 3, 4, 5};
int array_bak[5];
array_bak = array_org;
if (array_bak == array_org)
{
printf(“Copiedn”);
}
return 0;
}
Example
Waow!! so simple?
But can I do this?
Embedded C
Arrays – Copying
●
No!! its not so simple to copy two arrays as put in the
previous slide. C doesn't support it!
●
Then how to copy an array?
●
It has to be copied element by element
Embedded C
Arrays – Oops!! what is this now?
Pointers
Embedded C
Pointers – Jargon
●
What's a Jargon?
– Jargon may refer to terminology used in a certain
profession, such as computer jargon, or it may refer to any
nonsensical language that is not understood by most
people.
– Speech or writing having unusual or pretentious vocabulary,
convoluted phrasing, and vague meaning.
●
Pointer are perceived difficult
– Because of jargonification
●
So, let's dejargonify & understand them
Embedded C
Pointers – Analogy with Book
Front matter
Notes Section
Indexes
Contains pages
A Book
Boot Code
Data & Stack
Pointers to specific memory locations
Memory Pages
System Memory
Table of Contents Pointer to different programs
Chapters Code Segments
Embedded C
Pointers – Computers
●
Just like a book analogy, Computers contains different
different sections (Code) in the memory
●
All sections have different purposes
●
Every section has a address and we need to point to them
whenever required
●
In fact everything (Instructions and Data) in a particular
section has a address!!
●
So the pointer concept plays a big role here
Embedded C
Pointers – Why?
●
To have C as a low level language being a high level
language
●
Returning more than one value from a function
●
To achieve the similar results as of ”pass by variable”
●
parameter passing mechanism in function, by passing the
reference
●
To have the dynamic allocation mechanism
Embedded C
Pointers – The 7 Rules
●
Rule 1 - Pointer is an Integer
●
Rule 2 - Referencing and De-referencing
●
Rule 3 - Pointer means Containing
●
Rule 4 - Pointer Type
●
Rule 5 - Pointer Arithmetic
●
Rule 6 - Pointing to Nothing
●
Rule 7 - Static vs Dynamic Allocation
Embedded C
Pointers – The 7 Rules – Rule 1
CPU
RAM
Integer i;
Pointer p;
Say:
i = 6;
p = 6;
6
6
i
p
Embedded C
Pointers – The 7 Rules – Rule 1
●
Whatever we put in data bus is Integer
●
Whatever we put in address bus is Pointer
●
So, at concept level both are just numbers. May be of
different sized buses
●
Rule: “Pointer is an Integer”
●
Exceptions:
– May not be address and data bus of same size
– Rule 2 (Will see why? while discussing it)
Embedded C
Pointers – Rule 1 in detail
#include <stdio.h>
int main()
{
int x;
int *ptr;
x = 5;
ptr = 5;
return 0;
}
Example
?1000 Say 4 bytes
x
?2000 Say 4 bytes
ptr
Embedded C
Pointers – Rule 1 in detail
#include <stdio.h>
int main()
{
int x;
int *ptr;
x = 5;
ptr = 5;
return 0;
}
Example
51000 Say 4 bytes
x
52000 Say 4 bytes
ptr
●
So pointer is an integer
●
But remember the “They may not be of same size”
32 bit system = 4 Bytes
64 bit system = 8 Bytes
Embedded C
Pointers – The 7 Rules – Rule 2
●
Rule : “Referencing and Dereferencing”
Variable Address
&
*
Embedded C
Pointers – Rule 2 in detail
#include <stdio.h>
int main()
{
int x;
int *ptr;
x = 5;
return 0;
}
Example
51000 Say 4 bytes
x
?2000 Say 4 bytes
ptr
●
Considering the image, What would the below line mean?
* 1000
Embedded C
Pointers – Rule 2 in detail
#include <stdio.h>
int main()
{
int x;
int *ptr;
x = 5;
return 0;
}
Example
51000 Say 4 bytes
x
?2000 Say 4 bytes
ptr
●
Considering the image, What would the below line mean?
* 1000
●
Goto to the location 1000 and fetch its value, so
* 1000 5→
Embedded C
Pointers – Rule 2 in detail
#include <stdio.h>
int main()
{
int x;
int *ptr;
x = 5;
ptr = &x;
return 0;
}
Example
51000 Say 4 bytes
x
?2000 Say 4 bytes
ptr
●
What should be the change in the above diagram for the
above code?
Embedded C
Pointers – Rule 2 in detail
#include <stdio.h>
int main()
{
int x;
int *ptr;
x = 5;
ptr = &x;
return 0;
}
Example
51000 Say 4 bytes
x
10002000 Say 4 bytes
ptr
●
So pointer should contain the address of a variable
●
It should be a valid address
Embedded C
Pointers – Rule 2 in detail
#include <stdio.h>
int main()
{
int x;
int *ptr;
x = 5;
ptr = &x;
return 0;
}
Example
51000
x
10002000
ptr
“Add a & on variable to store its address in a pointer”
“Add a * on the pointer to extract the value of variable it is
pointing to”
& *
Embedded C
Pointers – Rule 2 in detail
#include <stdio.h>
int main()
{
int number = 10;
int *ptr;
ptr = &number;
printf(“Address of number is %pn”, &number);
printf(“ptr contains %pn”, ptr);
return 0;
}
Example
Embedded C
Pointers – Rule 2 in detail
#include <stdio.h>
int main()
{
int number = 10;
int *ptr;
ptr = &number;
printf(“number contains %dn”, number);
printf(“*ptr contains %dn”, *ptr);
return 0;
}
Example
Embedded C
Pointers – Rule 2 in detail
#include <stdio.h>
int main()
{
int number = 10;
int *ptr;
ptr = &number;
*ptr = 100;
printf(“number contains %dn”, number);
printf(“*ptr contains %dn”, *ptr);
return 0;
}
Example
●
By compiling and executing the above code we can
conclude
“*ptr = number”
Embedded C
Pointers – The 7 Rules – Rule 3
●
Pointer pointing to a Variable = Pointer contains the
Address of the Variable
●
Rule: “Pointing means Containing”
10
1000
1000
1004
1008
1012
1016
1020
1024
a
ptr
#include <stdio.h>
int main()
{
int a = 10;
int *ptr;
ptr = &a;
return 0;
}
Example
Embedded C
Pointers – The 7 Rules – Rule 4
●
Types to the pointers
●
What??, why do we need types attached to pointers?
Embedded C
Pointers – Rule 4 in detail
#include <stdio.h>
int main()
{
int num = 1234;
char ch;
return 0;
}
Example
12341000 4 bytes
num
?1004 1 bytes
ch
●
The question is, does address has a type?
●
So from the above above diagram can we say &num 4→
bytes and &ch 1 byte?→
Embedded C
Pointers – Rule 4 in detail
●
The answer is no!!, it does
not depend on the type of
the variable
●
The size of address
remains the same, and it
depends on the system we
use
●
Then a simple questions
arises is why types to
pointers?
1000
1004
1008
1012
1016
1020
1024
num
ch
Embedded C
Pointers – Rule 4 in detail
#include <stdio.h>
int main()
{
int num = 1234;
char ch;
int *iptr;
char *cptr;
return 0;
}
Example 1234
1000
num
?
1004
ch
●
Lets consider the above examples to understand it
●
Say we have a integer and a character pointer
?
2000
iptr
?
2004
cptr
Embedded C
Pointers – Rule 4 in detail
#include <stdio.h>
int main()
{
int num = 1234;
char ch;
int *iptr = &num;
char *cptr = &ch;
return 0;
}
Example 1234
1000
num
?
1004
ch
●
Lets consider the above examples to understand it
●
Say we have a integer and a character pointer
1000
2000
iptr
1004
2004
cptr
Embedded C
Pointers – Rule 4 in detail
1234
1000
num
?
1004
ch
●
With just the address, can
know what data is stored?
●
How would we know how
much data to fetch for the
address it is pointing to?
●
Eventually the answer would
be NO!!
●
So the type of the pointer is
required while
– Dereferencing it
– Doing pointer arithmetic
1000
2000
iptr
1004
2004
cptr
Embedded C
Pointers – Rule 4 in detail
1234
1000
num
?
1004
ch
●
When we say while
dereferencing, how does the
pointer know how much data
it should fetch at a time
●
From the diagram right side
we can say
*cptr fetches a single byte
*iptr fetches 4 consecutive
bytes
●
So as conclusion we can say
1000
2000
iptr
1004
2004
cptr
type * fetch sizeof(type) bytes→
Embedded C
Pointers – Rule 4 in detail - Endianness
●
Since the discussion is on the data fetching, its better
we have knowledge of storage concept of machines
●
The Endianness of the machine
●
What is this now!!?
– Its nothing but the byte ordering in a word of the
machine
●
There are two types
– Little Endian – LSB in Lower Memory Address
– Big Endian – MSB in Lower Memory Address
Embedded C
Pointers – Rule 4 in detail - Endianness
●
LSB
– The byte of a multi byte number with the least
importance
– The change in it would have least effect on complete
number
●
MSB
– The byte of a multi byte number with the most
importance
– The change in it would have more effect on complete
change number
Embedded C
Pointers – Rule 4 in detail - Endianness
●
Let us consider the following
example and how it would be
stored in both machine types
#include <stdio.h>
int main()
{
int num = 0x12345678;
return 0;
}
Example
1000
1004
78 56 34 12
num
1000
1004
12 34 56 78
num
Big Endian
Little Endian
1000
1000
78 56 34 12
12 34 56 78
1001
1001
1002
1002
1003
1003
→
→
Embedded C
Pointers – Rule 4 in detail - Endianness
●
OK Fine. What now? How is it going affect to fetch and
modification?
●
Let us consider the same example put in the previous
slide
#include <stdio.h>
int main()
{
int num = 0x12345678;
int *iptr, char *cptr;
iptr = &num;
cptr = &num;
return 0;
}
Example ●
First of all is it possible to
access a integer with character
pointer?
●
If yes, what should be the
effect on access?
●
Let us assume a Litte Endian
system
Embedded C
Pointers – Rule 4 in detail - Endianness
1000
78 56 34 12
num
1000
1000
2000 iptr
2004 cptr
*iptr = 0x12345678 *cptr = 0x78
●
So from the above diagram it should be clear that when we do
cross type accessing, the endianness should be considered
1000
78 56 34 12
num
1000
2000 iptr
1000
78 56 34 12
num
1000
2004 cptr
Embedded C
Pointers – The 7 Rules – Rule 4
●
So changing *cptr will change only
the byte its pointing to
#include <stdio.h>
int main()
{
int num = 0x12345678;
int *iptr = &num;
char *cptr = &num;
*cptr = 0x12;
return 0;
}
Example
*cptr = 0x12
1000
12 56 34 12
num
1000
2004 cptr
●
So *iptr would contain 0x12345612
now!!
Embedded C
Pointers – The 7 Rules – Rule 4
●
So as a summary the type to the pointer does not say its
type, but the type of the data its pointing to
●
So the size of the pointer for different types remains the
same
#include <stdio.h>
int main()
{
if (sizeof(char *) == sizeof(long long *))
{
printf(“Yes its Equaln”);
}
return 0;
}
Example
Embedded C
Pointers – The 7 Rules – Rule 4
●
Summarized as the following rule:
Rule: “Pointer of type t = t Pointer = (t *) = A variable,
which contains an address, which when dereferenced
returns a variable of type t, starting from that address”
Embedded C
Pointers – The 7 Rules – Rule 5
●
Pointer Arithmetic
Rule: “Value(p + i) = Value(p) + i * sizeof(*p)”
Embedded C
Pointers – The Rule 5 in detail
●
Before proceeding further let us understand an array
interpretation
– Original Big Variable
– Constant Pointer to the 1st Small Variable in the Big
Variable
– When first interpretation fails than second
interpretation comes to picture.
– The following are the case when first interpretation
fails:
●
When we pass array variable as function argument
●
When we assign a array variable to pointer variable
Embedded C
Pointers – The Rule 5 in detail
#include <stdio.h>
int main()
{
int array[5] = {1, 2, 3, 4, 5};
int *ptr = array;
return 0;
}
Example
1
2
3
4
5
1000
1000
1004
1008
1012
1016
1020
1024
ptr
●
So,
Address of array = 1000
Base address = 1000
&array[0] = 1 1000→
&array[1] = 2 1004→
array
Embedded C
Pointers – The Rule 5 in detail
#include <stdio.h>
int main()
{
int array[5] = {1, 2, 3, 4, 5};
int *ptr = array;
printf(“%dn”, *ptr);
return 0;
}
Example
1
2
3
4
5
1000
1000
1004
1008
1012
1016
1020
1024
array
ptr
●
This code should print 1 as output
since its points to the base address
●
Now, what should happen if we do
ptr = ptr + 1;
Embedded C
Pointers – The Rule 5 in detail
1
2
3
4
5
1004
1000
1004
1008
1012
1016
1020
1024
array
ptr
●
ptr = ptr + 1;
●
The above line can be discribed as
follows
●
ptr = ptr + 1 * sizeof(data type)
●
In this example we have a integer
array, so
●
ptr = ptr + 1 * sizeof(int)
ptr = ptr + 1 * 4
ptr = ptr + 4
●
Here ptr = 1000 so
ptr = 1000 + 4
ptr = 1004
Embedded C
Pointers – The Rule 5 in detail
1
2
3
4
5
1008
1000
1004
1008
1012
1016
1020
1024
array
ptr
ptr = ptr + 2;
1
2
3
4
5
1012
1000
1004
1008
1012
1016
1020
1024
array
ptr
ptr = ptr + 3;
1
2
3
4
5
1016
1000
1004
1008
1012
1016
1020
1024
array
ptr
ptr = ptr + 4;
●
Why does the compiler does this?. Just for convenience
Embedded C
Pointers – The Rule 5 in detail
●
Relation with array can be explained
as
ptr + 2
ptr + 2 * sizeof(int)
1000 + 2 * 4
1008 &array[2]→
●
So,
ptr + 2 1008 &array[2]→ →
*(ptr + 2) *(1008) array[2]→ →
1
2
3
4
5
1008
1000
1004
1008
1012
1016
1020
1024
array
ptr
ptr = ptr + 2;
Embedded C
Pointers – The Rule 5 in detail
●
So to access a array element using a pointer would be
*(ptr + i) array[i]→
●
This can be written as following too!!
array[i] *(array + i)→
●
Which results to
ptr = array
●
So as summary the below line also becomes valid because
of second array interpretation
int *ptr = array;
Embedded C
Pointers – The Rule 5 in detail
●
Wait can I write
*(ptr + i) *(i + ptr)→
●
Yes. So than can I write
array[i] i[array]→
●
Yes. You can index the element in both the ways
Embedded C
Pointers – The 7 Rules – Rule 5 – Size of void
●
On gcc size of void is 1
●
Hence pointer arithmetic can be performed on void
pointer
●
Its compiler dependent!
Note: To make standard compliant, compile using gcc -pedantic-errors
Embedded C
Pointers – The 7 Rules – Rule 6
●
Rule: “Pointer value of NULL or Zero = Null Addr = Null
Pointer = Pointing to Nothing”
Embedded C
Pointers – Rule 6 in detail – NULL Pointer
#include <stdio.h>
int main()
{
int *num;
return 0;
}
Example
?1000 4 bytes
num
?
?
?
?
?
Where am I
pointing to?
What does it
Contain?
Can I read or
write wherever
I am pointing?
Embedded C
Pointers – Rule 6 in detail – NULL Pointer
●
Is it pointing to the valid address?
●
If yes can we read or write in the location where its
pointing?
●
If no what will happen if we access that location?
●
So in summary where should we point to avoid all this
questions if we don't have a valid address yet?
●
The answer is Point to Nothing!!
Embedded C
Pointers – Rule 6 in detail – NULL Pointer
●
Now what is Point to Nothing?
●
A permitted location in the system will always give
predictable result!
●
It is possible that we are pointing to some memory location
within our program limit, which might fail any time! Thus
making it bit difficult to debug.
●
An act of initializing pointers to 0 (generally, implementation
dependent) at definition.
●
0??, Is it a value zero? So a pointer contain a value 0?
●
Yes. On most of the operating systems, programs are not
permitted to access memory at address 0 because that
memory is reserved by the operating system
Embedded C
Pointers – Rule 6 in detail – NULL Pointer
●
So by convention if a pointer is initialized to zero value,
it is logically understood to be point to nothing.
●
And now, in the pointer context, 0 is called as NULL
●
So a pointer that is assigned NULL is called a Null Pointer
which is Pointing to Nothing
●
So dereferencing a NULL pointer is illegal and will always
lead to segment violation, which is better than pointing
to some unknown location and failing randomly!
Embedded C
Pointers – Rule 6 in detail – NULL Pointer
●
Need for Pointing to 'Nothing'
– Terminating Linked Lists
– Indicating Failure by malloc, ...
●
Solution
– Need to reserve one valid value
– Which valid value could be most useless?
– In wake of OSes sitting from the start of memory, 0 is a
good choice
– As discussed in previous sides it is implementation
dependent
Embedded C
Pointers – Rule 6 in detail – NULL Pointer
#include <stdio.h>
int main()
{
int *num;
num = NULL;
return 0;
}
Example
#include <stdio.h>
int main()
{
int *num = NULL;
return 0;
}
Example
Embedded C
Pointers – The 7 Rules – Rule 7
●
Rule: “Static Allocation vs Dynamic Allocation”
#include <stdio.h>
int main()
{
int num1;
static int num2;
char *ptr;
char array[5];
return 0;
}
Example
#include <stdio.h>
int main()
{
char *ptr;
ptr = malloc(5);
return 0;
}
Example
Embedded C
Pointers – Rule 7 in detail
●
Unnamed vs named Allocation = Unnamed/named Houses
1 2 3 4 5 6 7 8
Ok, House 1, I should go that side ←
Ok, House 1, I should go??? Oops
Embedded C
Pointers – Rule 7 in detail
●
Managed by Compiler vs User
●
Compiler
– The compiler will allocate the required memory
internally
– This is done at the time of definition of variables
●
User
– The user has to allocate the memory whenever
required and deallocate whenever required
– This done by using malloc and free
Embedded C
Pointers – Rule 7 in detail
●
Static vs Dynamic
#include <stdio.h>
int main()
{
int num, *num_ptr, *ptr;
num_ptr = &num;
ptr = malloc(1);
return 0;
}
Example
?2000 4 bytes
num_ptr
?1000
num
?2004 4 bytes
ptr
Embedded C
Pointers – Rule 7 in detail
●
Static vs Dynamic
#include <stdio.h>
int main()
{
int num, *num_ptr, *ptr;
num_ptr = &num;
ptr = malloc(1);
return 0;
}
Example
10002000 4 bytes
num_ptr
?1000
num
?2004 4 bytes
ptr
Embedded C
Pointers – Rule 7 in detail
●
Static vs Dynamic
#include <stdio.h>
int main()
{
int num, *num_ptr, *ptr;
num_ptr = &num;
ptr = malloc(1);
return 0;
}
Example
10002000 4 bytes
num_ptr
?
?
?
?
?
?1000
num
5002004 4 bytes
ptr
500
Embedded C
Pointers – Rule 7 in detail - Dynamic Allocation
●
The need
– You can decide size of the memory at run time
– You can resize it whenever required
– You can decide when to create and destroy it.
Embedded C
Pointers – Rule 7 – Dynamic Allocation - malloc
Prototype
void *malloc(size_t size);
●
Allocates the requested size of memory from the heap
●
The size is in bytes
●
Returns the pointer of the allocated memory on success,
else returns NULL pointer
Embedded C
Pointers – Rule 7 – Dynamic Allocation - malloc
?
?
?
?
?
5001000
ptr
500
?
?
?
?
?
#include <stdio.h>
int main()
{
char *ptr;
ptr = malloc(5);
return 0;
}
Example
Allocate 5 Bytes
Embedded C
Pointers – Rule 7 – Dynamic Allocation - malloc
?
?
?
?
?
NULL1000
ptr
?
?
?
?
?
#include <stdio.h>
int main()
{
char *ptr;
ptr = malloc(10);
return 0;
}
Example
Only 7 Bytes
Available!!
So returns
NULL
NULL
Embedded C
Pointers – Rule 7 – Dynamic Allocation - calloc
Prototype
void *calloc(size_t nmemb, size_t size);
●
Allocates memory blocks large enough to hold "n
elements" of "size" bytes each, from the heap
●
The allocated memory is set with 0's
●
Returns the pointer of the allocated memory on success,
else returns NULL pointer
Embedded C
Pointers – Rule 7 – Dynamic Allocation - calloc
0
0
0
?
?
5001000
ptr
500
?
?
?
0
0
#include <stdio.h>
int main()
{
char *ptr;
ptr = calloc(5, 1);
return 0;
}
Example
Allocate 5 Bytes
and all are set
to zeros
Embedded C
Pointers – Rule 7 – Dynamic Allocation - realloc
Prototype
void *realloc(void *ptr, size_t size);
●
Changes the size of the already allocated memory by
malloc or calloc.
●
Returns the pointer of the allocated memory on success,
else returns NULL pointer
Embedded C
Pointers – Rule 7 – Dynamic Allocation - realloc
Example
?
?
?
?
?
5001000
ptr
500
?
?
?
?
?
Allocate 5 Bytes
#include <stdio.h>
int main()
{
char *ptr;
ptr = malloc(5);
ptr = realloc(ptr, 7);
ptr = realloc(ptr, 2);
return 0;
}
Embedded C
Pointers – Rule 7 – Dynamic Allocation - realloc
?
?
?
?
?
5001000
ptr
500
?
?
?
?
? Existing memory
gets extended to
7 bytes
Example
#include <stdio.h>
int main()
{
char *ptr;
ptr = malloc(5);
ptr = realloc(ptr, 7);
ptr = realloc(ptr, 2);
return 0;
}
Embedded C
Pointers – Rule 7 – Dynamic Allocation - realloc
?
?
?
?
?
5001000
ptr
500
?
?
?
?
? Existing memory
gets shrinked to
2 bytes
Example
#include <stdio.h>
int main()
{
char *ptr;
ptr = malloc(5);
ptr = realloc(ptr, 7);
ptr = realloc(ptr, 2);
return 0;
}
Embedded C
Pointers – Rule 7 – Dynamic Allocation - realloc
●
Points to be noted
– Reallocating existing memory will be like deallocating
the allocated memory
– If the requested chunk of memory cannot be
extended in the existing block, it would allocate in a
new free block starting from different memory!
●
So its always a good idea to store a reallocated
block in pointer, so that we can free the old
pointer.
Embedded C
Pointers – Rule 7 – Dynamic Deallocation - free
Prototype
void free(void *ptr);
●
Frees the allocated memory, which must have been
returned by a previous call to malloc(), calloc() or realloc()
●
Freeing an already freed block or any other block, would
lead to undefined behaviour
●
Freeing NULL pointer has no effect.
●
If free() is called with invalid argument, might collapse the
memory management mechanism
●
If free is not called after dynamic memory allocation, will
lead to memory leak
#include <stdio.h>
int main()
{
char *ptr;
int i;
ptr = malloc(5);
for (i = 0; i < 5; i++)
{
ptr[i] = 'A' + i;
}
free(ptr);
return 0;
}
Embedded C
Pointers – Rule 7 – Dynamic Deallocation - free
?
?
?
?
?
?1000
ptr
?
?
?
?
?
Example
#include <stdio.h>
int main()
{
char *ptr;
int i;
ptr = malloc(5);
for (i = 0; i < 5; i++)
{
ptr[i] = 'A' + i;
}
free(ptr);
return 0;
}
Embedded C
Pointers – Rule 7 – Dynamic Deallocation - free
?
?
?
?
?
5001000
ptr
?
?
?
?
?
500
Example
#include <stdio.h>
int main()
{
char *ptr;
int i;
ptr = malloc(5);
for (i = 0; i < 5; i++)
{
ptr[i] = 'A' + i;
}
free(ptr);
return 0;
}
Embedded C
Pointers – Rule 7 – Dynamic Deallocation - free
C
B
A
?
?
5001000
ptr
?
?
?
E
D
500
Example
Embedded C
Pointers – Rule 7 – Dynamic Deallocation - free
C
B
A
?
?
5001000
ptr
?
?
?
E
D
500
#include <stdio.h>
int main()
{
char *ptr;
int i;
ptr = malloc(5);
for (i = 0; i < 5; i++)
{
ptr[i] = 'A' + i;
}
free(ptr);
return 0;
}
Example
Embedded C
Pointers – Rule 7 – Dynamic Deallocation - free
●
Points to be noted
– Free releases the allocated block, but the pointer
would still be pointing to the same block!!, So
accessing the freed block will have undefined
behaviour.
– This type of pointer which are pointing to freed
locations are called as Dangling Pointers
– Doesn't clear the memory after freeing
Will meet again

More Related Content

What's hot (20)

PDF
C Programming - Refresher - Part III
Emertxe Information Technologies Pvt Ltd
 
PPTX
Embedded C programming session10
Keroles karam khalil
 
PPT
Embedded _c_
Moorthy Peesapati
 
PDF
Embedded Operating System - Linux
Emertxe Information Technologies Pvt Ltd
 
PDF
Embedded C - Optimization techniques
Emertxe Information Technologies Pvt Ltd
 
PDF
C Programming - Refresher - Part II
Emertxe Information Technologies Pvt Ltd
 
PDF
Embedded C - Lecture 3
Mohamed Abdallah
 
PPT
linux device driver
Rahul Batra
 
PDF
C Programming - Refresher - Part I
Emertxe Information Technologies Pvt Ltd
 
PDF
Embedded C - Lecture 2
Mohamed Abdallah
 
PDF
The Internals of "Hello World" Program
National Cheng Kung University
 
PPT
U Boot or Universal Bootloader
Satpal Parmar
 
PPT
Embedded c program and programming structure for beginners
Kamesh Mtec
 
PDF
Embedded Android : System Development - Part II (Linux device drivers)
Emertxe Information Technologies Pvt Ltd
 
PPTX
CS304PC:Computer Organization and Architecture Session 23 Decimal Arithmetic ...
Guru Nanak Technical Institutions
 
C Programming - Refresher - Part III
Emertxe Information Technologies Pvt Ltd
 
Embedded C programming session10
Keroles karam khalil
 
Embedded _c_
Moorthy Peesapati
 
Embedded Operating System - Linux
Emertxe Information Technologies Pvt Ltd
 
Embedded C - Optimization techniques
Emertxe Information Technologies Pvt Ltd
 
C Programming - Refresher - Part II
Emertxe Information Technologies Pvt Ltd
 
Embedded C - Lecture 3
Mohamed Abdallah
 
linux device driver
Rahul Batra
 
C Programming - Refresher - Part I
Emertxe Information Technologies Pvt Ltd
 
Embedded C - Lecture 2
Mohamed Abdallah
 
The Internals of "Hello World" Program
National Cheng Kung University
 
U Boot or Universal Bootloader
Satpal Parmar
 
Embedded c program and programming structure for beginners
Kamesh Mtec
 
Embedded Android : System Development - Part II (Linux device drivers)
Emertxe Information Technologies Pvt Ltd
 
CS304PC:Computer Organization and Architecture Session 23 Decimal Arithmetic ...
Guru Nanak Technical Institutions
 

Similar to Embedded C - Day 1 (20)

DOCX
C tutorials
Amit Kapoor
 
PDF
Introduction of c_language
SINGH PROJECTS
 
PPTX
Lecture 2
marvellous2
 
PPTX
Introduction to C language programming.pptx
OVIDMAMAH
 
PPTX
Introductionof c
Phanibabu Komarapu
 
PDF
Embedded-C.pdf
Mritunjaykumar502565
 
DOCX
C notes
Raunak Sodhi
 
PPSX
Lecture 2
Mahfuzur Rahman
 
PPT
All C ppt.ppt
JeelBhanderi4
 
PPTX
PPS_unit_2_gtu_sem_2_year_2023_GTUU.pptx
ZwecklosSe
 
PPTX
Introduction-to-C-Programming (1ggggggggggggggggg).pptx
middollaganeshreddy0
 
PDF
Basic of the C language
Sachin Verma
 
DOC
Basic c
Veera Karthi
 
PDF
C programming_MSBTE_Diploma_Pranoti Doke
Pranoti Doke
 
PDF
Embedded C programming based on 8051 microcontroller
Gaurav Verma
 
PPT
bits.ppt
MMichaelGuelcan
 
PPT
10 instruction sets characteristics
Sher Shah Merkhel
 
PPTX
2. Introduction to 'C' Language (1).pptx
AkshatMuke1
 
DOCX
C and DS -unit 1 -Artificial Intelligence and ML.docx
msurfudeen6681
 
PPT
C presentation book
krunal1210
 
C tutorials
Amit Kapoor
 
Introduction of c_language
SINGH PROJECTS
 
Lecture 2
marvellous2
 
Introduction to C language programming.pptx
OVIDMAMAH
 
Introductionof c
Phanibabu Komarapu
 
Embedded-C.pdf
Mritunjaykumar502565
 
C notes
Raunak Sodhi
 
Lecture 2
Mahfuzur Rahman
 
All C ppt.ppt
JeelBhanderi4
 
PPS_unit_2_gtu_sem_2_year_2023_GTUU.pptx
ZwecklosSe
 
Introduction-to-C-Programming (1ggggggggggggggggg).pptx
middollaganeshreddy0
 
Basic of the C language
Sachin Verma
 
Basic c
Veera Karthi
 
C programming_MSBTE_Diploma_Pranoti Doke
Pranoti Doke
 
Embedded C programming based on 8051 microcontroller
Gaurav Verma
 
bits.ppt
MMichaelGuelcan
 
10 instruction sets characteristics
Sher Shah Merkhel
 
2. Introduction to 'C' Language (1).pptx
AkshatMuke1
 
C and DS -unit 1 -Artificial Intelligence and ML.docx
msurfudeen6681
 
C presentation book
krunal1210
 
Ad

More from Emertxe Information Technologies Pvt Ltd (20)

Ad

Recently uploaded (20)

PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Digital Circuits, important subject in CS
contactparinay1
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 

Embedded C - Day 1

  • 1. Team Emertxe C Come let's see how deep it is!! Day 1
  • 3. C Have you ever pondered how - powerful it is? - efficient it is? - flexible it is? - deep you can explore your system?
  • 4. C Brief History ● Prior to C, most of the computer languages (such as Algol) – Academic oriented, unrealistic and were generally defined by committees. – Designed having application domain in mind (Non portable) ● It has lineage starting from CPL – Martin Richards implemented BCPL – Ken Thompson further refined BCPL to a language named as B – Dennis M. Ritchie added types to B and created a language C ● With just 32 keywords, C established itself in a very wide base of applications.
  • 5. C Where is it used? ● System Software Development ● Embedded Software Development ● OS Kernel Development ● Firmware, Middle-ware and Driver Development ● File System Development And many more!!
  • 6. C Important Characteristics ● Considered as a middle level language ● Can be considered as a pragmatic language. ● It is indented to be used by advanced programmers, for serious use, and not for novices and thus qualify less as an academic language for learning ● Gives importance to curt code. ● It is widely available in various platforms from mainframes to palmtops and is known for its wide availability
  • 7. C Important Characteristics ● It is a general-purpose language, even though it is applied and used effectively in various specific domains ● It is a free-formatted language (and not a strongly-typed language) ● Efficiency and portability are the important considerations ● Library facilities play an important role
  • 8. C Standard ● “The C programming language” book served as a primary reference for C programmers and implementers alike for nearly a decade ● However it didn’t define C perfectly and there were many ambiguous parts in the language ● As far as the library was concerned, only the C implementation in UNIX was close to the ’standard’ ● So many dialects existed for C and it was the time the language has to be standardized and it was done in 1989 with ANSI C standard ● Nearly after a decade another standard, C9X, for C is available that provides many significant improvements over the previous 1989 ANSI C standard
  • 9. C Keywords ● In programming, a keyword is a word that is reserved by a program because the word has a special meaning ● Keywords can be commands or parameters ● Every programming language has a set of keywords that cannot be used as variable names ● Keywords are sometimes called reserved names
  • 10. C Keywords - Categories Type Keyword Data Types char int float double Modifiers signed unsigned short long Qualifiers const volatile Loops for while do Jump goto break continue Type Keyword Decision if else switch case default Storage Class auto register static extern Derived struct unions User defined enums typedefs Others void return sizeof
  • 11. C Typical C Code Contents Documentation Preprocessor Statements Global Declaration The Main Code: -------------------- Local Declarations Program Statements Function Calls One or many Function(s): --------------------------------- The function body ● A typical code might contain the blocks shown on left side ● It is generally recommended to practice writing codes with all the blocks
  • 12. C Anatomy of a Simple C Code /* My first C code */ #include <stdio.h> int main() { /* To display Hello world */ printf("Hello worldn"); return 0; } File Header Preprocessor Directive The start of program Comment Statement Program Termination
  • 13. C Compilation ● Assuming your code is ready, use the following commands to compile the code ● On command prompt, type $ gcc <file_name>.c ● This will generate a executable named a.out ● But it is recommended that you follow proper conversion even while generating your code, so you could use $ gcc <file_name>.c -o <file_name> ● This will generate a executable named <file_name>
  • 14. C Execution ● To execute your code you shall try $ ./a.out ● If you have named you output file as your <file_name> then $ ./<file_name> ● This should the expected result on your system
  • 16. Embedded C Number Systems ● A number is generally represented as – Decimal – Octal – Hexadecimal – Binary Dec 0 0 0 0 Oct Hex Bin 0 0 0 0 10 8 16 2 Type Base 0 0 0 0 0 0 00 0 0 11 1 1 0 0 0 00 0 1 02 2 2 0 0 0 00 0 1 13 3 3 0 0 0 00 1 0 04 4 4 0 0 0 00 1 0 15 5 5 0 0 0 00 1 1 06 6 6 0 0 0 00 1 1 17 7 7 0 0 0 01 0 0 08 10 8 0 0 0 01 0 0 19 11 9 0 0 0 01 0 1 010 12 A 0 0 0 01 0 1 111 13 B 0 0 0 01 1 0 012 14 C 0 0 0 01 1 0 113 15 D 0 0 0 01 1 1 014 16 E 0 0 0 01 1 1 115 17 F Decimal Type Range (8 Bits) Octal Hexadecimal Binary 0b00000000 - 0b11111111 0 - 255 000 - 0377 0x00 - 0xFF
  • 17. Embedded C Data Representation - Bit ● Literally computer understand only two states HIGH and LOW making it a binary system ● These states are coded as 1 or 0 called binary digits ● “Binary Digit” gave birth to the word “Bit” ● Bit is known a basic unit of information in computer and digital communication 0 Value No of Bits 0 1 1
  • 18. Embedded C Data Representation - Byte ● A unit of digital information ● Commonly consist of 8 bits ● Considered smallest addressable unit of memory in computer 0 Value No of Bits 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
  • 19. Embedded C Data Representation - Character ● One byte represents one unique character like 'A', 'b', '1', '$' ... ● Its possible to have 256 different combinations of 0s and 1s to form a individual character ● There are different types of character code representation like – ASCII American Standard Code for Information→ Interchange – 7 Bits (Extended - 8 Bits) – EBCDIC Extended BCD Interchange Code – 8 Bits→ – Unicode Universal Code - 16 Bits and more→
  • 20. Embedded C Data Representation - Character ● ASCII is the oldest representation ● Please try the following on command prompt to know the available codes $ man ascii ● Can be represented by char datatype 0 Value No of Bits A 0 0 0 1 1 0 1 0 0 0 0 0 0 0 0 1
  • 21. Embedded C Data Representation - Word ● Amount of data that a machine can fetch and process at one time ● An integer number of bytes, for example, one, two, four, or eight ● General discussion on the bitness of the system is references to the word size of a system, i.e., a 32 bit chip has a 32 bit (4 Bytes) word size 0 Value No of Bits 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
  • 22. Embedded C Integer Number - Positive ● Integers are like whole numbers, but allow negative numbers and no fraction ● An example of 1310 in 32 bit system would be Position Bit No of Bits Value 31 0 30 0 29 0 28 0 27 0 26 0 25 0 24 0 23 0 22 0 21 0 20 0 19 0 18 0 17 0 16 0 15 0 14 0 13 0 12 0 11 0 10 0 9 0 8 0 7 0 6 0 5 0 4 0 3 1 2 1 1 0 0 1
  • 23. Embedded C Integer Number - Negative ● Negative Integers represented with the 2's complement of the positive number ● An example of -1310 in 32 bit system would be Position Bit No of Bits Value 31 0 30 0 29 0 28 0 27 0 26 0 25 0 24 0 23 0 22 0 21 0 20 0 19 0 18 0 17 0 16 0 15 0 14 0 13 0 12 0 11 0 10 0 9 0 8 0 7 0 6 0 5 0 4 0 3 1 2 1 1 0 0 1 1's Compli 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 0 Add 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2's Compli 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 ● Mathematically : -k 2≡ n - k ● Negative Integers represented with the 2's complement of the positive number ● An example of -1310 in 32 bit system would be
  • 24. Embedded C Float Point Number ● A formulaic representation which approximates a real number ● Computers are integer machines and are capable of representing real numbers only by using complex codes ● The most popular code for representing real numbers is called the IEEE Floating-Point Standard Sign Exponent Mantissa Float (32 bits) Single Precision 1 bit 8 bits 23 bits Double (64 bits) Double Precision 1 bit 11 bits 52 bits
  • 26. Embedded C Basic Data Types Data Types Integral Floating Point char int float double
  • 27. Embedded C Data Type Modifiers and Qualifiers Modifiers Size Signedness short long long signed unsigned long T T T T T Qualifiers const volatile V V V Variables T Data Types F Functions Notes: - ANSI says, ensure that: char ≤ short ≤ int ≤ long - unsigned float in not supported
  • 28. Embedded C Data Type and Function storage modification Storage Modifiers auto extern register inline static V V V V F F F V Variables T Data Types F Functions
  • 30. Embedded C Code Statements - Simple int main() { number = 5; 3; +5; sum = number + 5; 4 + 5; ; } Assignment statement Valid statement, But smart compilers might remove it Assignment statement. Result of the number + 5 will be assigned to sum Valid statement, But smart compilers might remove it This valid too!!
  • 31. Embedded C Code Statements - Compound int main() { ... if (num1 > num2) { if (num1 > num3) { printf(“Hello”); } else { printf(“World”); } } ... } If conditional statement Nested if statement
  • 32. Embedded C Conditional Constructs Conditional Constructs Multi iteration Single iteration for do while while if and its family switch case
  • 33. Embedded C Conditional Constructs - if #include <stdio.h> int main() { int num1 = 2; if (num1 < 5) { printf(“num1 < 5n”); } printf(“num1 is %dn”, num1); return 0; } ExampleSyntax if (condition) { statement(s); } Flow cond? true code false
  • 34. Embedded C Conditional Constructs – if else Syntax if (condition) { statement(s); } else { statement(s); } Flow cond? true code false code
  • 35. Embedded C Conditional Constructs – if else #include <stdio.h> int main() { int num1 = 10; if (num1 < 5) { printf(“num1 < 5n”); } else { printf(“num1 > 5n”); } return 0; } Example
  • 36. Embedded C Conditional Constructs – if else if Syntax if (condition1) { statement(s); } else if (condition2) { statement(s); } else { statement(s); } Flow cond1? code true false cond2? code code true false
  • 37. Embedded C Conditional Constructs – if else if #include <stdio.h> int main() { int num1 = 10; if (num1 < 5) { printf(“num1 < 5n”); } else if (num1 > 5) { printf(“num1 > 5n”); } else { printf(“num1 = 5n”); } return 0; } Example
  • 38. Embedded C Conditional Constructs – switch Syntax switch (expression) { case constant: statement(s); break; case constant: statement(s); break; case constant: statement(s); break; default: statement(s); } Flow expr code true false case1? break case2? default code break code break true false
  • 39. Embedded C Conditional Constructs - switch #include <stdio.h> int main() { int option; printf(“Enter the valuen”); scanf(“%d”, &option); switch (option) { case 10: printf(“You entered 10n”); break; case 20: printf(“You entered 20n”); break; default: printf(“Try againn”); } return 0; } Example
  • 40. Embedded C Conditional Constructs – while Syntax while (condition) { statement(s); } Flow false true cond? code #include <stdio.h> int main() { int i; i = 0; while (i < 10) { printf(“Looped %d timesn”, i); i++; } return 0; } Example ● Controls the loop. ● Evaluated before each execution of loop body
  • 41. Embedded C Conditional Constructs – do while Syntax do { statement(s); } while (condition); Flow false true cond? code #include <stdio.h> int main() { int i; i = 0; do { printf(“Looped %d timesn”, i); i++; } while (i < 10); return 0; } Example ● Controls the loop. ● Evaluated after each execution of loop body
  • 42. Embedded C Conditional Constructs – for Syntax for (init; condition; post evaluation expr) { statement(s); } Flow init false true cond? code post eval expr #include <stdio.h> int main() { int i; for (i = 0; i < 10; i++) { printf(“Looped %d timesn”, i); } return 0; } Example ● Controls the loop. ● Evaluated before each execution of loop body
  • 43. Embedded C Conditional Constructs – continue Syntax do { conditional statement continue; } while (condition); Flow ● A continue statement causes a jump to the loop-continuation portion, that is, to the end of the loop body ● The execution of code appearing after the continue will be skipped ● Can be used in any type of multi iteration loop false true loop cond? code block cond? false continue? true code block
  • 44. Embedded C Conditional Constructs – continue #include <stdio.h> int main() { int i; for (i = 0; i < 10; i++) { if (i == 5) { continue; } printf(“%dn”, i); } return 0; } Example
  • 45. Embedded C Conditional Constructs – break Syntax do { conditional statement break; } while (condition); Flow ● A break statement shall appear only in “switch body” or “loop body” ● “break” is used to exit the loop, the statements appearing after break in the loop will be skipped false true loop cond? code block cond? false break? true
  • 46. Embedded C Conditional Constructs – break #include <stdio.h> int main() { int i; for (i = 0; i < 10; i++) { if (i == 5) { break; } printf(“%dn”, i); } return 0; } Example
  • 47. Embedded C Conditional Constructs – break #include <stdio.h> int main() { int i; for (i = 0; i < 10; i++) { if (i == 5) { break; } printf(“%dn”, i); } printf(“%dn”, i); return 0; } Example
  • 49. Embedded C Operators ● Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands ● All C operators do 2 things – Operates on its Operands – Returns a value
  • 50. Embedded C Operators Category Operand Operation unary ternary Arithmetic Logical binary + ! Relational > Assignment = Bitwise & Language sizeof() Pointers * - * / % || && < <= >= == != | ^ ~ >> << & -> ... ... ... ...
  • 51. Embedded C Operators – Precedence and Associativity Operators Associativity Precedence () [] -> . L - R HIGH ! ++ −− - + * & (type) sizeof∼ R - L / % * L - R + - L - R << >> L - R < <= > >= L - R == != L - R & L - R ^ L - R | L - R && L - R || L - R ?: R - L = += -= *= /= %= &= ^= |= <<= >>= R - L , L - R LOW Note: post ++ and –- operators have higher precedence than pre ++ and –- operators (Rel-99 spec)
  • 52. Embedded C Operators - Arithmetic #include <stdio.h> int main() { int num1 = 0, num2 = 0; printf(“sum is %dn”, num1++ + ++num2); return 0; } Example What will be the output? Operator Description Associativity * / % Multiplication Division Modulo L to R + - Addition Subtraction R to L
  • 54. Embedded C Type Conversion Hierarchy signed char unsigned char signed short unsigned short signed int unsigned int signed long unsigned long signed long long unsigned long long float double long double
  • 55. Embedded C Type Conversion - Implicit ● Automatic Unary conversions – The result of + and - are promoted to int if operands are char and short – The result of ~ and ! is integer ● Automatic Binary conversions – If one operand is of LOWER RANK (LR) data type & other is of HIGHER RANK (HR) data type then LOWER RANK will be converted to HIGHER RANK while evaluating the expression. – Example: LR + HR LR converted to HR→
  • 56. Embedded C Type Conversion - Implicit ● Type promotion – LHS type is HR and RHS type is LR → int = char LR is promoted→ to HR while assigning ● Type demotion – LHS is LR and RHS is HR → int = float HR rank will be demoted→ to LR. Truncated
  • 57. Embedded C Type Conversion – Explicit (Type Casting) #include <stdio.h> int main() { int num1 = 5, num2 = 3; float num3 = (float) num1 / num2; printf(“num3 is %fn”, num3); return 0; } Example Syntax (data type) expression
  • 58. Embedded C Operators - Logical #include <stdio.h> int main() { int num1 = 1, num2 = 0; if (++num1 || num2++) { printf(“num1 is %d num2 is %dn”, num1, num2); } num1 = 1, num2 = 0; if (num1++ && ++num2) { printf(“num1 is %d num2 is %dn”, num1, num2); } else { printf(“num1 is %d num2 is %dn”, num1, num2); } return 0; } Example What will be the output? Operator Description Associativity ! && || Logical NOT Logical AND Logical OR R to L L to R L to R
  • 59. Embedded C Operators - Relational #include <stdio.h> int main() { float num1 = 0.7; if (num1 == 0.7) { printf(“Yes, it is equaln”); } else { printf(“No, it is not equaln”); } return 0; } Example Operator Description Associativity > < >= <= == != Greater than Lesser than Greater than or equal Lesser than or equal Equal to Not Equal to L to R What will be the output?
  • 60. Embedded C Operators - Assignment #include <stdio.h> int main() { int num1 = 1, num2 = 1; float num3 = 1.7, num4 = 1.5; num1 += num2 += num3 += num4; printf(“num1 is %dn”, num1); return 0; } Example #include <stdio.h> int main() { float num1 = 1; if (num1 = 1) { printf(“Yes, it is equal!!n”); } else { printf(“No, it is not equaln”); } return 0; } Example
  • 61. Embedded C Operators - Bitwise ● Bitwise operators perform operations on bits ● The operand type shall be integral ● Return type is integral value
  • 62. Embedded C Operators - Bitwise 0x61 Value 0x13 0 0 1 0 1 0 0 1 0 0 0 0 0 1 1 1 00x60 Value 0x13 A Operand B 0x01 0 0 0 0 0 0 0 10x13A & B & Bitwise AND Bitwise ANDing of all the bits in two operands 0x61 Value 0x13 0 0 1 0 1 0 0 1 0 0 0 0 0 1 1 1 00x60 Value 0x13 A Operand B 0x73 0 1 1 1 0 0 1 10x13A | B | Bitwise OR Bitwise ORing of all the bits in two operands 0x61 Value 0x13 0 0 1 0 1 0 0 1 0 0 0 0 0 1 1 1 00x60 Value 0x13 A Operand B 0x72 0 1 1 1 0 0 1 00x13A ^ B ^ Bitwise XOR Bitwise XORing of all the bits in two operands
  • 63. Embedded C Operators - Bitwise 0x61 Value 0 1 1 0 0 0 0 100x60 Value A Operand 0x9E 1 0 0 1 1 1 1 00x13~A ~ Compliment Complimenting all the bits of the operand 0x61 Value 0 1 1 0 0 0 0 100x60 Value A Operand 0x18 0 0 0 1 1 0 0 00x13A >> 2 >> Right Shift Shift all the bits right n times by introducing zeros left 0x61 Value 0 1 1 0 0 0 0 100x60 Value A Operand 0x84 1 0 0 0 0 1 0 00x13A << 2 << Left Shift Shift all the bits left n times by introducing zeros right
  • 64. Embedded C Operators – Bitwise – Left Shift 'Value' << 'Bits Count' ● Value : Is shift operand on which bit shifting effect to be applied ● Bits count : By how many bit(s) the given “Value” to be shifted 0x61Original value 0x84 A << 2 Resultant value 0000110 1 0100001 0 Say A = 91 Zero filling left shift
  • 65. Embedded C Operators – Bitwise – Right Shift 'Value' >> 'Bits Count' ● Value : Is shift operand on which bit shifting effect to be applied ● Bits count : By how many bit(s) the given “Value” to be shifted Zero filling right shift 0x61Original value 0x18 A >> 2 Resultant value 0000110 1 0011000 0 Say A = 91
  • 66. Embedded C Operators – Bitwise – Right Shift – Signed Valued “Signed Value' >> 'Bits Count' ● Same operation as mentioned in previous slide. ● But the sign bits gets propagated. Zero filling right shiftSign bit filling right shift 0xA1Original value 0xE8 A >> 2 Resultant value 0000101 1 0010111 0 Say A = -95
  • 67. Embedded C Operators - Bitwise #include <stdio.h> int main() { int count; unsigned char num = 0xFF; for (count = 0; num != 0; num >>= 1) { if (num & 01) { count++; } } printf(“count is %dn”, count); return 0; } Example
  • 68. Embedded C Operators – Language - sizeof() #include <stdio.h> int main() { int num = 5; printf(“%u:%u:%un”, sizeof(int), sizeof num, sizeof 5); return 0; } Example #include <stdio.h> int main() { int num1 = 5; int num2 = sizeof(++num1); printf(“num1 is %d and num2 is %dn”, num1, num2); return 0; } Example
  • 69. Embedded C Operators – Language - sizeof() ● 3 reasons for why sizeof is not a function – Any type of operands, – Type as an operand, – No brackets needed across operands
  • 70. Embedded C Operators – Ternary Syntax Condition ? Expression 1 : Expression 2; #include <stdio.h> int main() { int num1 = 10; int num2 = 20; int num3; if (num1 > num2) { num3 = num1; } else { num3 = num2; } printf(“%dn”, num3); return 0; } Example #include <stdio.h> int main() { int num1 = 10; int num2 = 20; int num3; num3 = num1 > num2 ? num1 : num2; printf(“Greater num is %dn”, num3); return 0; }
  • 71. Embedded C Operators – Comma ● The left operand of a comma operator is evaluated as a void expression: Then the right operand is evaluated, the result has its type and value ● Comma acts as separator (not an operator) in following cases – Arguments to functions – Lists of initializers (variable declarations) ● But, can be used with parentheses as function arguments such as - – foo ((x = 2, x + 3)); // final value of argument is 5
  • 72. Embedded C Over and Underflow ● 8-bit Integral types can hold certain ranges of values ● So what happens when we try to traverse this boundary? Overflow (127 + 1) Underflow (-128 - 1)
  • 73. Embedded C Overflow – Signed Numbers 0x7FOriginal value 0x80Resultant value 1111110 1 Say A = +127 1Add 0000000 1 0000001 0
  • 74. Embedded C Underflow – Signed Numbers 0x80Original value 0x7FResultant value Say A = -128 -1Add 0000001 0 1111111 1 1111110 11
  • 75. Array
  • 76. Embedded C Arrays – Know the Concept Ends here Starts here A conveyor belt Equally spaced Defined length Carry similar items Index as 10th item
  • 77. Embedded C Arrays – Know the Concept Conveyor Belt Top view First Element Start (Base) address Last Element End address ● Total Elements ● Fixed size ● Contiguous Address ● Elements are accessed by indexing ● Legal access region An Array
  • 78. Embedded C Arrays Syntax data_type name[SIZE]; Where SIZE is number of elements The size for the array would be SIZE * <size of data_type> Example int age[5] = {10, 20, 30, 40, 50}; 10 20 30 40 50 Index 1 Index 2 Index 3 Index 4 Index 5 baseaddr baseaddr+4 baseaddr+8 baseaddr+12 baseaddr+16
  • 79. Embedded C Arrays – Point to be noted ● An array is a collection of data of same data type. ● Addresses are sequential ● First element with lowest address and the last element with highest address ● Indexing starts from 0 and should end at array SIZE – 1. Example say array[5] will have to be indexed from 0 to 4 ● Any access beyond the boundaries would be illegal access Example, You should not access array[-1] or array[SIZE]
  • 80. Embedded C Arrays – Why? #include <stdio.h> int main() { int num1 = 10; int num2 = 20; int num3 = 30; int num4 = 40; int num5 = 50; printf(“%dn”, num1); printf(“%dn”, num2); printf(“%dn”, num3); printf(“%dn”, num4); printf(“%dn”, num5); return 0; } Example #include <stdio.h> int main() { int num_array[5] = {10, 20, 30, 40, 50}; int index; for (index = 0; index < 5; index++) { printf(“%dn”, num_array[index]); } return 0; }
  • 81. Embedded C Arrays - Reading #include <stdio.h> int main() { int array[5] = {1, 2, 3, 4, 5}; int index; index = 0; do { printf(“Index %d has Element %dn”, index, array[index]); index++; } while (index < 5); return 0; } Example
  • 82. Embedded C Arrays - Storing #include <stdio.h> int main() { int num_array[5]; int index; for (index = 0; index < 5; index++) { scanf(“%d”, &num_array[index]); } return 0; } Example
  • 83. Embedded C Arrays - Initializing #include <stdio.h> int main() { int array1[5] = {1, 2, 3, 4, 5}; int array2[5] = {1, 2}; int array3[] = {1, 2}; int array4[]; /* Invalid */ printf(“%un”, sizeof(array1)); printf(“%un”, sizeof(array2)); printf(“%un”, sizeof(array3)); return 0; } Example
  • 84. Embedded C Arrays – Copying ● Can we copy 2 arrays? If yes how? #include <stdio.h> int main() { int array_org[5] = {1, 2, 3, 4, 5}; int array_bak[5]; array_bak = array_org; if (array_bak == array_org) { printf(“Copiedn”); } return 0; } Example Waow!! so simple? But can I do this?
  • 85. Embedded C Arrays – Copying ● No!! its not so simple to copy two arrays as put in the previous slide. C doesn't support it! ● Then how to copy an array? ● It has to be copied element by element
  • 86. Embedded C Arrays – Oops!! what is this now?
  • 88. Embedded C Pointers – Jargon ● What's a Jargon? – Jargon may refer to terminology used in a certain profession, such as computer jargon, or it may refer to any nonsensical language that is not understood by most people. – Speech or writing having unusual or pretentious vocabulary, convoluted phrasing, and vague meaning. ● Pointer are perceived difficult – Because of jargonification ● So, let's dejargonify & understand them
  • 89. Embedded C Pointers – Analogy with Book Front matter Notes Section Indexes Contains pages A Book Boot Code Data & Stack Pointers to specific memory locations Memory Pages System Memory Table of Contents Pointer to different programs Chapters Code Segments
  • 90. Embedded C Pointers – Computers ● Just like a book analogy, Computers contains different different sections (Code) in the memory ● All sections have different purposes ● Every section has a address and we need to point to them whenever required ● In fact everything (Instructions and Data) in a particular section has a address!! ● So the pointer concept plays a big role here
  • 91. Embedded C Pointers – Why? ● To have C as a low level language being a high level language ● Returning more than one value from a function ● To achieve the similar results as of ”pass by variable” ● parameter passing mechanism in function, by passing the reference ● To have the dynamic allocation mechanism
  • 92. Embedded C Pointers – The 7 Rules ● Rule 1 - Pointer is an Integer ● Rule 2 - Referencing and De-referencing ● Rule 3 - Pointer means Containing ● Rule 4 - Pointer Type ● Rule 5 - Pointer Arithmetic ● Rule 6 - Pointing to Nothing ● Rule 7 - Static vs Dynamic Allocation
  • 93. Embedded C Pointers – The 7 Rules – Rule 1 CPU RAM Integer i; Pointer p; Say: i = 6; p = 6; 6 6 i p
  • 94. Embedded C Pointers – The 7 Rules – Rule 1 ● Whatever we put in data bus is Integer ● Whatever we put in address bus is Pointer ● So, at concept level both are just numbers. May be of different sized buses ● Rule: “Pointer is an Integer” ● Exceptions: – May not be address and data bus of same size – Rule 2 (Will see why? while discussing it)
  • 95. Embedded C Pointers – Rule 1 in detail #include <stdio.h> int main() { int x; int *ptr; x = 5; ptr = 5; return 0; } Example ?1000 Say 4 bytes x ?2000 Say 4 bytes ptr
  • 96. Embedded C Pointers – Rule 1 in detail #include <stdio.h> int main() { int x; int *ptr; x = 5; ptr = 5; return 0; } Example 51000 Say 4 bytes x 52000 Say 4 bytes ptr ● So pointer is an integer ● But remember the “They may not be of same size” 32 bit system = 4 Bytes 64 bit system = 8 Bytes
  • 97. Embedded C Pointers – The 7 Rules – Rule 2 ● Rule : “Referencing and Dereferencing” Variable Address & *
  • 98. Embedded C Pointers – Rule 2 in detail #include <stdio.h> int main() { int x; int *ptr; x = 5; return 0; } Example 51000 Say 4 bytes x ?2000 Say 4 bytes ptr ● Considering the image, What would the below line mean? * 1000
  • 99. Embedded C Pointers – Rule 2 in detail #include <stdio.h> int main() { int x; int *ptr; x = 5; return 0; } Example 51000 Say 4 bytes x ?2000 Say 4 bytes ptr ● Considering the image, What would the below line mean? * 1000 ● Goto to the location 1000 and fetch its value, so * 1000 5→
  • 100. Embedded C Pointers – Rule 2 in detail #include <stdio.h> int main() { int x; int *ptr; x = 5; ptr = &x; return 0; } Example 51000 Say 4 bytes x ?2000 Say 4 bytes ptr ● What should be the change in the above diagram for the above code?
  • 101. Embedded C Pointers – Rule 2 in detail #include <stdio.h> int main() { int x; int *ptr; x = 5; ptr = &x; return 0; } Example 51000 Say 4 bytes x 10002000 Say 4 bytes ptr ● So pointer should contain the address of a variable ● It should be a valid address
  • 102. Embedded C Pointers – Rule 2 in detail #include <stdio.h> int main() { int x; int *ptr; x = 5; ptr = &x; return 0; } Example 51000 x 10002000 ptr “Add a & on variable to store its address in a pointer” “Add a * on the pointer to extract the value of variable it is pointing to” & *
  • 103. Embedded C Pointers – Rule 2 in detail #include <stdio.h> int main() { int number = 10; int *ptr; ptr = &number; printf(“Address of number is %pn”, &number); printf(“ptr contains %pn”, ptr); return 0; } Example
  • 104. Embedded C Pointers – Rule 2 in detail #include <stdio.h> int main() { int number = 10; int *ptr; ptr = &number; printf(“number contains %dn”, number); printf(“*ptr contains %dn”, *ptr); return 0; } Example
  • 105. Embedded C Pointers – Rule 2 in detail #include <stdio.h> int main() { int number = 10; int *ptr; ptr = &number; *ptr = 100; printf(“number contains %dn”, number); printf(“*ptr contains %dn”, *ptr); return 0; } Example ● By compiling and executing the above code we can conclude “*ptr = number”
  • 106. Embedded C Pointers – The 7 Rules – Rule 3 ● Pointer pointing to a Variable = Pointer contains the Address of the Variable ● Rule: “Pointing means Containing” 10 1000 1000 1004 1008 1012 1016 1020 1024 a ptr #include <stdio.h> int main() { int a = 10; int *ptr; ptr = &a; return 0; } Example
  • 107. Embedded C Pointers – The 7 Rules – Rule 4 ● Types to the pointers ● What??, why do we need types attached to pointers?
  • 108. Embedded C Pointers – Rule 4 in detail #include <stdio.h> int main() { int num = 1234; char ch; return 0; } Example 12341000 4 bytes num ?1004 1 bytes ch ● The question is, does address has a type? ● So from the above above diagram can we say &num 4→ bytes and &ch 1 byte?→
  • 109. Embedded C Pointers – Rule 4 in detail ● The answer is no!!, it does not depend on the type of the variable ● The size of address remains the same, and it depends on the system we use ● Then a simple questions arises is why types to pointers? 1000 1004 1008 1012 1016 1020 1024 num ch
  • 110. Embedded C Pointers – Rule 4 in detail #include <stdio.h> int main() { int num = 1234; char ch; int *iptr; char *cptr; return 0; } Example 1234 1000 num ? 1004 ch ● Lets consider the above examples to understand it ● Say we have a integer and a character pointer ? 2000 iptr ? 2004 cptr
  • 111. Embedded C Pointers – Rule 4 in detail #include <stdio.h> int main() { int num = 1234; char ch; int *iptr = &num; char *cptr = &ch; return 0; } Example 1234 1000 num ? 1004 ch ● Lets consider the above examples to understand it ● Say we have a integer and a character pointer 1000 2000 iptr 1004 2004 cptr
  • 112. Embedded C Pointers – Rule 4 in detail 1234 1000 num ? 1004 ch ● With just the address, can know what data is stored? ● How would we know how much data to fetch for the address it is pointing to? ● Eventually the answer would be NO!! ● So the type of the pointer is required while – Dereferencing it – Doing pointer arithmetic 1000 2000 iptr 1004 2004 cptr
  • 113. Embedded C Pointers – Rule 4 in detail 1234 1000 num ? 1004 ch ● When we say while dereferencing, how does the pointer know how much data it should fetch at a time ● From the diagram right side we can say *cptr fetches a single byte *iptr fetches 4 consecutive bytes ● So as conclusion we can say 1000 2000 iptr 1004 2004 cptr type * fetch sizeof(type) bytes→
  • 114. Embedded C Pointers – Rule 4 in detail - Endianness ● Since the discussion is on the data fetching, its better we have knowledge of storage concept of machines ● The Endianness of the machine ● What is this now!!? – Its nothing but the byte ordering in a word of the machine ● There are two types – Little Endian – LSB in Lower Memory Address – Big Endian – MSB in Lower Memory Address
  • 115. Embedded C Pointers – Rule 4 in detail - Endianness ● LSB – The byte of a multi byte number with the least importance – The change in it would have least effect on complete number ● MSB – The byte of a multi byte number with the most importance – The change in it would have more effect on complete change number
  • 116. Embedded C Pointers – Rule 4 in detail - Endianness ● Let us consider the following example and how it would be stored in both machine types #include <stdio.h> int main() { int num = 0x12345678; return 0; } Example 1000 1004 78 56 34 12 num 1000 1004 12 34 56 78 num Big Endian Little Endian 1000 1000 78 56 34 12 12 34 56 78 1001 1001 1002 1002 1003 1003 → →
  • 117. Embedded C Pointers – Rule 4 in detail - Endianness ● OK Fine. What now? How is it going affect to fetch and modification? ● Let us consider the same example put in the previous slide #include <stdio.h> int main() { int num = 0x12345678; int *iptr, char *cptr; iptr = &num; cptr = &num; return 0; } Example ● First of all is it possible to access a integer with character pointer? ● If yes, what should be the effect on access? ● Let us assume a Litte Endian system
  • 118. Embedded C Pointers – Rule 4 in detail - Endianness 1000 78 56 34 12 num 1000 1000 2000 iptr 2004 cptr *iptr = 0x12345678 *cptr = 0x78 ● So from the above diagram it should be clear that when we do cross type accessing, the endianness should be considered 1000 78 56 34 12 num 1000 2000 iptr 1000 78 56 34 12 num 1000 2004 cptr
  • 119. Embedded C Pointers – The 7 Rules – Rule 4 ● So changing *cptr will change only the byte its pointing to #include <stdio.h> int main() { int num = 0x12345678; int *iptr = &num; char *cptr = &num; *cptr = 0x12; return 0; } Example *cptr = 0x12 1000 12 56 34 12 num 1000 2004 cptr ● So *iptr would contain 0x12345612 now!!
  • 120. Embedded C Pointers – The 7 Rules – Rule 4 ● So as a summary the type to the pointer does not say its type, but the type of the data its pointing to ● So the size of the pointer for different types remains the same #include <stdio.h> int main() { if (sizeof(char *) == sizeof(long long *)) { printf(“Yes its Equaln”); } return 0; } Example
  • 121. Embedded C Pointers – The 7 Rules – Rule 4 ● Summarized as the following rule: Rule: “Pointer of type t = t Pointer = (t *) = A variable, which contains an address, which when dereferenced returns a variable of type t, starting from that address”
  • 122. Embedded C Pointers – The 7 Rules – Rule 5 ● Pointer Arithmetic Rule: “Value(p + i) = Value(p) + i * sizeof(*p)”
  • 123. Embedded C Pointers – The Rule 5 in detail ● Before proceeding further let us understand an array interpretation – Original Big Variable – Constant Pointer to the 1st Small Variable in the Big Variable – When first interpretation fails than second interpretation comes to picture. – The following are the case when first interpretation fails: ● When we pass array variable as function argument ● When we assign a array variable to pointer variable
  • 124. Embedded C Pointers – The Rule 5 in detail #include <stdio.h> int main() { int array[5] = {1, 2, 3, 4, 5}; int *ptr = array; return 0; } Example 1 2 3 4 5 1000 1000 1004 1008 1012 1016 1020 1024 ptr ● So, Address of array = 1000 Base address = 1000 &array[0] = 1 1000→ &array[1] = 2 1004→ array
  • 125. Embedded C Pointers – The Rule 5 in detail #include <stdio.h> int main() { int array[5] = {1, 2, 3, 4, 5}; int *ptr = array; printf(“%dn”, *ptr); return 0; } Example 1 2 3 4 5 1000 1000 1004 1008 1012 1016 1020 1024 array ptr ● This code should print 1 as output since its points to the base address ● Now, what should happen if we do ptr = ptr + 1;
  • 126. Embedded C Pointers – The Rule 5 in detail 1 2 3 4 5 1004 1000 1004 1008 1012 1016 1020 1024 array ptr ● ptr = ptr + 1; ● The above line can be discribed as follows ● ptr = ptr + 1 * sizeof(data type) ● In this example we have a integer array, so ● ptr = ptr + 1 * sizeof(int) ptr = ptr + 1 * 4 ptr = ptr + 4 ● Here ptr = 1000 so ptr = 1000 + 4 ptr = 1004
  • 127. Embedded C Pointers – The Rule 5 in detail 1 2 3 4 5 1008 1000 1004 1008 1012 1016 1020 1024 array ptr ptr = ptr + 2; 1 2 3 4 5 1012 1000 1004 1008 1012 1016 1020 1024 array ptr ptr = ptr + 3; 1 2 3 4 5 1016 1000 1004 1008 1012 1016 1020 1024 array ptr ptr = ptr + 4; ● Why does the compiler does this?. Just for convenience
  • 128. Embedded C Pointers – The Rule 5 in detail ● Relation with array can be explained as ptr + 2 ptr + 2 * sizeof(int) 1000 + 2 * 4 1008 &array[2]→ ● So, ptr + 2 1008 &array[2]→ → *(ptr + 2) *(1008) array[2]→ → 1 2 3 4 5 1008 1000 1004 1008 1012 1016 1020 1024 array ptr ptr = ptr + 2;
  • 129. Embedded C Pointers – The Rule 5 in detail ● So to access a array element using a pointer would be *(ptr + i) array[i]→ ● This can be written as following too!! array[i] *(array + i)→ ● Which results to ptr = array ● So as summary the below line also becomes valid because of second array interpretation int *ptr = array;
  • 130. Embedded C Pointers – The Rule 5 in detail ● Wait can I write *(ptr + i) *(i + ptr)→ ● Yes. So than can I write array[i] i[array]→ ● Yes. You can index the element in both the ways
  • 131. Embedded C Pointers – The 7 Rules – Rule 5 – Size of void ● On gcc size of void is 1 ● Hence pointer arithmetic can be performed on void pointer ● Its compiler dependent! Note: To make standard compliant, compile using gcc -pedantic-errors
  • 132. Embedded C Pointers – The 7 Rules – Rule 6 ● Rule: “Pointer value of NULL or Zero = Null Addr = Null Pointer = Pointing to Nothing”
  • 133. Embedded C Pointers – Rule 6 in detail – NULL Pointer #include <stdio.h> int main() { int *num; return 0; } Example ?1000 4 bytes num ? ? ? ? ? Where am I pointing to? What does it Contain? Can I read or write wherever I am pointing?
  • 134. Embedded C Pointers – Rule 6 in detail – NULL Pointer ● Is it pointing to the valid address? ● If yes can we read or write in the location where its pointing? ● If no what will happen if we access that location? ● So in summary where should we point to avoid all this questions if we don't have a valid address yet? ● The answer is Point to Nothing!!
  • 135. Embedded C Pointers – Rule 6 in detail – NULL Pointer ● Now what is Point to Nothing? ● A permitted location in the system will always give predictable result! ● It is possible that we are pointing to some memory location within our program limit, which might fail any time! Thus making it bit difficult to debug. ● An act of initializing pointers to 0 (generally, implementation dependent) at definition. ● 0??, Is it a value zero? So a pointer contain a value 0? ● Yes. On most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system
  • 136. Embedded C Pointers – Rule 6 in detail – NULL Pointer ● So by convention if a pointer is initialized to zero value, it is logically understood to be point to nothing. ● And now, in the pointer context, 0 is called as NULL ● So a pointer that is assigned NULL is called a Null Pointer which is Pointing to Nothing ● So dereferencing a NULL pointer is illegal and will always lead to segment violation, which is better than pointing to some unknown location and failing randomly!
  • 137. Embedded C Pointers – Rule 6 in detail – NULL Pointer ● Need for Pointing to 'Nothing' – Terminating Linked Lists – Indicating Failure by malloc, ... ● Solution – Need to reserve one valid value – Which valid value could be most useless? – In wake of OSes sitting from the start of memory, 0 is a good choice – As discussed in previous sides it is implementation dependent
  • 138. Embedded C Pointers – Rule 6 in detail – NULL Pointer #include <stdio.h> int main() { int *num; num = NULL; return 0; } Example #include <stdio.h> int main() { int *num = NULL; return 0; } Example
  • 139. Embedded C Pointers – The 7 Rules – Rule 7 ● Rule: “Static Allocation vs Dynamic Allocation” #include <stdio.h> int main() { int num1; static int num2; char *ptr; char array[5]; return 0; } Example #include <stdio.h> int main() { char *ptr; ptr = malloc(5); return 0; } Example
  • 140. Embedded C Pointers – Rule 7 in detail ● Unnamed vs named Allocation = Unnamed/named Houses 1 2 3 4 5 6 7 8 Ok, House 1, I should go that side ← Ok, House 1, I should go??? Oops
  • 141. Embedded C Pointers – Rule 7 in detail ● Managed by Compiler vs User ● Compiler – The compiler will allocate the required memory internally – This is done at the time of definition of variables ● User – The user has to allocate the memory whenever required and deallocate whenever required – This done by using malloc and free
  • 142. Embedded C Pointers – Rule 7 in detail ● Static vs Dynamic #include <stdio.h> int main() { int num, *num_ptr, *ptr; num_ptr = &num; ptr = malloc(1); return 0; } Example ?2000 4 bytes num_ptr ?1000 num ?2004 4 bytes ptr
  • 143. Embedded C Pointers – Rule 7 in detail ● Static vs Dynamic #include <stdio.h> int main() { int num, *num_ptr, *ptr; num_ptr = &num; ptr = malloc(1); return 0; } Example 10002000 4 bytes num_ptr ?1000 num ?2004 4 bytes ptr
  • 144. Embedded C Pointers – Rule 7 in detail ● Static vs Dynamic #include <stdio.h> int main() { int num, *num_ptr, *ptr; num_ptr = &num; ptr = malloc(1); return 0; } Example 10002000 4 bytes num_ptr ? ? ? ? ? ?1000 num 5002004 4 bytes ptr 500
  • 145. Embedded C Pointers – Rule 7 in detail - Dynamic Allocation ● The need – You can decide size of the memory at run time – You can resize it whenever required – You can decide when to create and destroy it.
  • 146. Embedded C Pointers – Rule 7 – Dynamic Allocation - malloc Prototype void *malloc(size_t size); ● Allocates the requested size of memory from the heap ● The size is in bytes ● Returns the pointer of the allocated memory on success, else returns NULL pointer
  • 147. Embedded C Pointers – Rule 7 – Dynamic Allocation - malloc ? ? ? ? ? 5001000 ptr 500 ? ? ? ? ? #include <stdio.h> int main() { char *ptr; ptr = malloc(5); return 0; } Example Allocate 5 Bytes
  • 148. Embedded C Pointers – Rule 7 – Dynamic Allocation - malloc ? ? ? ? ? NULL1000 ptr ? ? ? ? ? #include <stdio.h> int main() { char *ptr; ptr = malloc(10); return 0; } Example Only 7 Bytes Available!! So returns NULL NULL
  • 149. Embedded C Pointers – Rule 7 – Dynamic Allocation - calloc Prototype void *calloc(size_t nmemb, size_t size); ● Allocates memory blocks large enough to hold "n elements" of "size" bytes each, from the heap ● The allocated memory is set with 0's ● Returns the pointer of the allocated memory on success, else returns NULL pointer
  • 150. Embedded C Pointers – Rule 7 – Dynamic Allocation - calloc 0 0 0 ? ? 5001000 ptr 500 ? ? ? 0 0 #include <stdio.h> int main() { char *ptr; ptr = calloc(5, 1); return 0; } Example Allocate 5 Bytes and all are set to zeros
  • 151. Embedded C Pointers – Rule 7 – Dynamic Allocation - realloc Prototype void *realloc(void *ptr, size_t size); ● Changes the size of the already allocated memory by malloc or calloc. ● Returns the pointer of the allocated memory on success, else returns NULL pointer
  • 152. Embedded C Pointers – Rule 7 – Dynamic Allocation - realloc Example ? ? ? ? ? 5001000 ptr 500 ? ? ? ? ? Allocate 5 Bytes #include <stdio.h> int main() { char *ptr; ptr = malloc(5); ptr = realloc(ptr, 7); ptr = realloc(ptr, 2); return 0; }
  • 153. Embedded C Pointers – Rule 7 – Dynamic Allocation - realloc ? ? ? ? ? 5001000 ptr 500 ? ? ? ? ? Existing memory gets extended to 7 bytes Example #include <stdio.h> int main() { char *ptr; ptr = malloc(5); ptr = realloc(ptr, 7); ptr = realloc(ptr, 2); return 0; }
  • 154. Embedded C Pointers – Rule 7 – Dynamic Allocation - realloc ? ? ? ? ? 5001000 ptr 500 ? ? ? ? ? Existing memory gets shrinked to 2 bytes Example #include <stdio.h> int main() { char *ptr; ptr = malloc(5); ptr = realloc(ptr, 7); ptr = realloc(ptr, 2); return 0; }
  • 155. Embedded C Pointers – Rule 7 – Dynamic Allocation - realloc ● Points to be noted – Reallocating existing memory will be like deallocating the allocated memory – If the requested chunk of memory cannot be extended in the existing block, it would allocate in a new free block starting from different memory! ● So its always a good idea to store a reallocated block in pointer, so that we can free the old pointer.
  • 156. Embedded C Pointers – Rule 7 – Dynamic Deallocation - free Prototype void free(void *ptr); ● Frees the allocated memory, which must have been returned by a previous call to malloc(), calloc() or realloc() ● Freeing an already freed block or any other block, would lead to undefined behaviour ● Freeing NULL pointer has no effect. ● If free() is called with invalid argument, might collapse the memory management mechanism ● If free is not called after dynamic memory allocation, will lead to memory leak
  • 157. #include <stdio.h> int main() { char *ptr; int i; ptr = malloc(5); for (i = 0; i < 5; i++) { ptr[i] = 'A' + i; } free(ptr); return 0; } Embedded C Pointers – Rule 7 – Dynamic Deallocation - free ? ? ? ? ? ?1000 ptr ? ? ? ? ? Example
  • 158. #include <stdio.h> int main() { char *ptr; int i; ptr = malloc(5); for (i = 0; i < 5; i++) { ptr[i] = 'A' + i; } free(ptr); return 0; } Embedded C Pointers – Rule 7 – Dynamic Deallocation - free ? ? ? ? ? 5001000 ptr ? ? ? ? ? 500 Example
  • 159. #include <stdio.h> int main() { char *ptr; int i; ptr = malloc(5); for (i = 0; i < 5; i++) { ptr[i] = 'A' + i; } free(ptr); return 0; } Embedded C Pointers – Rule 7 – Dynamic Deallocation - free C B A ? ? 5001000 ptr ? ? ? E D 500 Example
  • 160. Embedded C Pointers – Rule 7 – Dynamic Deallocation - free C B A ? ? 5001000 ptr ? ? ? E D 500 #include <stdio.h> int main() { char *ptr; int i; ptr = malloc(5); for (i = 0; i < 5; i++) { ptr[i] = 'A' + i; } free(ptr); return 0; } Example
  • 161. Embedded C Pointers – Rule 7 – Dynamic Deallocation - free ● Points to be noted – Free releases the allocated block, but the pointer would still be pointing to the same block!!, So accessing the freed block will have undefined behaviour. – This type of pointer which are pointing to freed locations are called as Dangling Pointers – Doesn't clear the memory after freeing