C programming session9 -

Preview:

Citation preview

C_ProgrammingPart 9

ENG. KEROLES SHENOUDA

1

Brainstorming on previous session

2

3

Thanks to Eng. Amr for solving it 4

https://github.com/AmrHRAbdeen/C-Programming

Dynamic allocation 8

Malloc() 9

calloc() 10

free() 11

12

13

14

C-typedef 15

16

C - Preprocessor 17

18

19

Embedded C Programming

20

useful references for

C and Embedded C

DIFFERENCE BETWEEN C AND EMBEDDED C

Compilers for C (ANSI C) typically generate OS dependantexecutables. Embedded C requires compilers to create files to be downloaded to the microcontrollers/microprocessors where it needs to run. Embedded compilers give access to all resources which is not provided in compilers for desktop computer applications.

23

DIFFERENCE BETWEEN C AND EMBEDDED C

C is used for desktop computers, while embedded C is for microcontroller based applications. Accordingly, C has the luxury to use resources of a desktop PC like memory, OS, etc. While programming on desktop systems, we need not bother about memory. However, embedded C has to use with the limited resources (RAM, ROM, I/Os) on an embedded processor. Thus, program code must fit into the available program memory. If code exceeds the limit, the system is likely to crash.

24

DIFFERENCE BETWEEN C AND EMBEDDED C

Embedded systems often have the real-time constraints, which is usually not there with desktop computer applications.

Embedded systems often do not have a console, which is available in case of desktop applications.

So, what basically is different while programming with embedded C is the mindset; for embedded applications, we need to optimally use the resources, make the program code efficient, and satisfy real time constraints, if any. All this is done using the basic constructs, syntaxes, and function libraries of ‘C’.

25

Embedded C Constrains

Memory

Power

Size

Cost

Timing

CPU

26

SW Should be

Portable

Maintainable

Optimized

Reusable

Readable

27

Embedded versus Desktop Programming

Main characteristics of an Embedded programming environment:• Limited ROM.• Limited RAM.• Limited stack space.• Hardware oriented programming.• Critical timing (Interrupt Service Routines, tasks, …).• Many different pointer kinds (far / near / rom / uni / paged / …).• Special keywords and tokens (@, interrupt, tiny, …)

28

Assembly versus C 29

Why Change to C

C is much more flexible than other high-level programming languages:• C is a structured language.• C is a relatively small language.• C has very loose data typing.• C easily supports low-level bit-wise data manipulation.• C is sometimes referred to as a “high-level assembly language”.► When compared to assembly language programming:• Code written in C can be more reliable.• Code written in C can be more scalable.• Code written in C can be more portable between different platforms.• Code written in C can be easier to maintain.• Code written in C can be more productive

30

How to make Code more Readable

31

1.Commenting 32

2.memory-mapped devices

Documenting the source code is helpful not only for your future reference but for those who come after you. For instance, if you're working on an embedded system, you need to have a memory map indicating where all the memory-mapped devices can be found. Listing 8 shows an example of a memory map.

33

Review: The “super loop” software architecture

ProblemWhat is the minimum software environment you need to create anembedded C program?

Solution

34

Review: An introduction to schedulers

Many embedded systems must carry out tasks at particular instantsof time. More specifically, we have two kinds of activity toperform:• Periodic tasks, to be performed (say) once every 100 ms,and - less commonly -• One-shot tasks, to be performed once after a delay of (say)50 ms.

35

Function Reuse 36

Header File 37

Header File

Each .h file should be “stand alone”

▫ It should declare, #define, and typedef anything needed by prototypes and include any .h files it needs to avoid compiler errors

In our example prototypes for CircleArea() and Circumference are placed in circleUtils.h ▫ circleUtils.h included in circleUtils.c ▫ circleUtils.h included in any other .c file that uses CircleArea()

38

Guarding Header Files 39

Guarding Example 40

Separate Compilation

If code is separated into multiple .c files

▫ Must compile each .c file

▫ Combine resulting .o files to create executable

41

Program Organization 42

Scope/Lifetime

Variable “scope” refers to part of the programthat may access the variable▫ Local, global, etc…• Variable “lifetime” refers to time in which avariable occupies memory• Both determined by how and where variable isdefined

43

Storage classes

In C language, each variable has a storage class which decides scope, visibility and lifetime of that variable. The following storage classes are most oftenlyused in C programming,

Automatic variables

External variables

Static variables

Register variables

44

Automatic variables

A variable declared inside a function without any storage class specification, is by default an automatic variable. They are created when a function is called and are destroyed automatically when the function exits. Automatic variables can also be called local variables because they are local to a function. By default they are assigned garbage value by the compiler.

45

External or Global variable

A variable that is declared outside any function is a Global variable. Global variables remain available throughout the entire program. One important thing to remember about global variable is that their values can be changed by any function in the program.

46

Here the global variable number is available to all three

functions.

extern keyword

The extern keyword is used before a variable to inform the compiler that this

variable is declared somewhere else. The extern declaration does not allocate storage for variables.

47

Problem when extern is not used 48

Example Using extern in same file 49

Static variables

A static variable tells the compiler to persist the variable until the end of program. Instead of creating and destroying a variable every time when it comes into and goes out of scope, static is initialized only once and remains into existence till the end of program. A static variable can either be internal or external depending upon the place of declaraction. Scope of internal static variable remains inside the function in which it is defined. External static variables remain restricted to scope of file in each they are declared.

They are assigned 0 (zero) as default value by the compiler.

50

Static variables 51

Register variable

Register variable inform the compiler to store the variable in register instead of memory. Register variable has faster access than normal variable. Frequently used variables are kept in register. Only few variables can be placed inside register.

NOTE : We can never get the address of such variables.

Syntax :

52

Volatile Type Qualifier 53

How to define u8 ,u32,…. 54

Modularity 55

UART.c

UART_init ()

{

……

pDATA_recieve = F1 ;

}

ISR()

{ if (pDATA_recieve != NULL)

pDATA_recieve (uDR);

}

56

APP

ECU

HAL

HW

UART

F1();

UART.hVoid (* pDATA_recieve )(char);

#pragma

The #pragma directive gives special instructions to the compiler. The #pragma directive is especially useful in embedded C programming and can tell the compiler to allocate a certain variable in RAM or EEPROM. It can also tell the compiler to insert a snippet of assembly language code.

The GNU GCC compiler, which is a popular compiler for various embedded architectures such as ARM and AVR, also uses attributes as an alternative syntax to the #pragma directive.

57

#pragma GCC dependencyallows you to check the relative dates of the current file and another file. If the other file is more recent than the current file, a warning is issued.

This is useful if the current file is derived from the other file,

and should be regenerated. The other file is searched for using the normal include search path.

Optional trailing text can be used to give more information in the warning message.

C Startup

It is not possible to directly execute C code, when the processor comes out of reset. Since, unlike assembly language, C programs need some basic pre-requisites to be satisfied. This section will describe the pre-requisites and how to meet the pre-requisites.

We will take the example of C program that calculates the sum of an array as an example. And by the end of this section, we will be able to perform the necessary setup, transfer control to the C code and execute it.

58

59Listing 12. Sum of Array in C

Before transferring control to C code, the following have to be setup correctly.

Stack

Global variables

Initialized

Uninitialized

Read-only data

60

Stack

C uses the stack for storing local (auto) variables, passing function arguments, storing return address, etc. So it is essential that the stack be setup correctly, before transferring control to C code.

Stacks are highly flexible in the ARM architecture, since the implementation is completely left to the software.

61

Stack 62

So all that has to be done in the startup code is to point r13 at the highest RAM address, so that the stack can grow downwards (towards lower addresses). For the connex board this can be acheived using the following ARM instruction.

Global Variables

When C code is compiled, the compiler places initialized global variables in the .data section. So just as with the assembly, the .data has to be copied from Flash to RAM.

The C language guarantees that all uninitialized global variables will be initialized to zero. When C programs are compiled, a separate section called .bss is used for uninitialized variables. Since the value of these variables are all zeroes to start with, they do not have to be stored in Flash. Before transferring control to C code, the memory locations corresponding to these variables have to be initialized to zero.

63

Read-only Data

GCC places global variables marked as const in a separate section, called .rodata. The .rodata is also used for storing string constants.

Since contents of .rodata section will not be modified, they can be placed in Flash. The linker script has to modified to accomodate this.

64

Startup Code

65

Linker Script for C code 66

The startup code has the following parts 67

1.exception vectors

2.code to copy the .data from Flash to RAM

3.code to zero out the .bss4.code to setup the stack pointer

5.branch to main

Startup Assembly 68

Data Structures

69

Introduction to Data Structures

Data Structure is a way of collecting and organising data in such a way that we can perform operations on these data in an effective way

70

Basic types of Data Structures

anything that can store data can be called as a data strucure, hence Integer, Float, Boolean, Char etc, all are data structures. They are known as Primitive Data Structures.

Then we also have some complex Data Structures, which are used to store large and connected data. Some example of Abstract Data Structure are :

Linked List

Tree

Graph

Stack, Queue etc.

All these data structures allow us to perform different operations on data. We select these data structures based on which type of operation is required

71

Basic types of Data Structures 72

Stacks

Stack is an abstract data type with a bounded(predefined) capacity. It is a simple data structure that allows adding and removing elements in a particular order. Every time an element is added, it goes on the top of the stack, the only element that can be removed is the element that was at the top of the stack, just like a pile of objects.

73

Basic features of Stack

Stack is an ordered list of similar data type.

Stack is a LIFO structure. (Last in First out).

push() function is used to insert new elements into the Stack and pop() is used to delete an element from the stack. Both insertion and deletion are allowed at only one end of Stack called Top.

Stack is said to be in Overflow state when it is completely full and is said to be in Underflow state if it is completely empty.

74

Applications of Stack

The simplest application of a stack is to reverse a word. You push a given word to stack - letter by letter - and then pop letters from the stack.

75

Implementation of Stack

Stack can be easily implemented using an Array or a Linked List. Arrays are quick, but are limited in size and Linked List requires overhead to allocate, link, unlink, and deallocate, but is not limited in size. Here we will implement Stack using array.

76

Stack Implementation with Array 77

Stack Implementation with Array 78

Stack Implementation with Array 79

Stack Implementation with Array 80

Stack Implementation with Array 81

Stack Implementation with Array 82

Stack Implementation with Array 83

Stack Implementation with Array 84

Stack Implementation with Array 85

Status of Stack

Position of Top Status of Stack

-1 Stack is Empty

0 Only one element in Stack

N-1 Stack is Full

N Overflow state of Stack

86

Basic Operations

Stack operations may involve initializing the stack, using it and then de-initializing it. Apart from these basic stuffs, a stack is used for the following two primary operations −

push() − pushing (storing) an element on the stack.

pop() − removing (accessing) an element from the stack.

When data is PUSHed onto stack.

To use a stack efficiently we need to check status of stack as well. For the same purpose, the following functionality is added to stacks −

peek() − get the top data element of the stack, without removing it.

isFull() − check if stack is full.

isEmpty() − check if stack is empty.

87

Basic Operations 88

int peek()

{ return stack[top]; }

isfull()

peek()

bool isfull() {

if(top == MAXSIZE)

return true;

else

return false;

}

isempty()

bool isempty()

{

if(top == -1)

return true;

else

return false;

}

PUSH Operation 89

The process of putting a new data element onto stack is known as PUSHOperation. Push operation involves series of steps −

•Step 1 − Check if stack is full.•Step 2 − If stack is full, produce error and exit.•Step 3 − If stack is not full, increment top to point next empty space.•Step 4 − Add data element to the stack location, where top is pointing.•Step 5 − return success.

if linked-list is used to implement stack, then in step 3, we need to allocate space dynamically.

PUSH Operation 90

void push(int data)

{

if(!isFull())

{ top = top + 1;

stack[top] = data;

}else {

printf("Could not insert data, Stack is full.\n");

}

}

Pop Operation 91

A POP operation may involve the following steps −

•Step 1 − Check if stack is empty.•Step 2 − If stack is empty, produce error and exit.•Step 3 − If stack is not empty, access the data element at which top is pointing.•Step 4 − Decrease the value of top by 1.•Step 5 − return success.

92

Stack Code 93

Queue Data Structures

Queue is also an abstract data type or a linear data structure, in which the first element is inserted from one end called REAR(also called tail), and the deletion of exisitingelement takes place from the other end called asFRONT(also called head). This makes queue as FIFO data structure, which means that element inserted first will also be removed first.

The process to add an element into queue is called Enqueue and the process of removal of an element from queue is called Dequeue.

94

Queue

Queue is an abstract data structure, somewhat similar to Stack. In contrast to Queue, queue is opened at both end. One end is always used to insert data (enqueue) and the other is used to remove data (dequeue). Queue follows First-In-First-Out methodology, i.e., the data item stored first will be accessed first.

95

Queue

Same as Queue, queue can also be implemented using Array, Linked-list, Pointer and Structures. For the sake of simplicity we shall implement queue using one-dimensional array.

96

Queue Basic Operations

Queue operations may involve initializing or defining the queue, utilizing it and then completing erasing it from memory. Here we shall try to understand basic operations associated with queues −

enqueue() − add (store) an item to the queue.

dequeue() − remove (access) an item from the queue.

Few more functions are required to make above mentioned queue operation efficient. These are −

peek() − get the element at front of the queue without removing it.

isfull() − checks if queue is full.

isempty() − checks if queue is empty.

In queue, we always dequeue (or access) data, pointed by front pointer and while enqueing (or storing) data in queue we take help of rear pointer.

97

Queue Implementation with Array 98

Queue Implementation with Array 99

Queue Implementation with Array 100

Queue Implementation with Array 101

Queue Implementation with Array 102

Queue Implementation with Array 103

Queue Implementation with Array 104

Queue Implementation with Array 105

Queue Implementation with Array 106

Queue Implementation with Array 107

Queue Implementation with Array 108

Queue Implementation with Array 109

Queue Implementation with Array 110

Queue Implementation with Array 111

Queue Implementation with Array 112

Queue Implementation with Array 113

Queue Implementation with Array 114

Queue Implementation with Array 115

Queue Implementation with Array 116

Queue Implementation with Array 117

Queue Implementation with Array 118

Queue Implementation with Array 119

Queue Implementation with Array 120

Queue

peek()

isfull()

121

Queue

isempty()

122

Enqueue Operation

Step 1 − Check if queue is full.

Step 2 − If queue is full, produce overflow error and exit.

Step 3 − If queue is not full, increment rear pointer to point next empty space.

Step 4 − Add data element to the queue location, where rear is pointing.

Step 5 − return success.

123

Enqueue Operation 124

Dequeue Operation

Step 1 − Check if queue is empty.

Step 2 − If queue is empty, produce underflow error and exit.

Step 3 − If queue is not empty, access data where frontis pointing.

Step 3 − Increment front pointer to point next available data element.

Step 5 − return success.

125

Data Structure - Linked List

A linked-list is a sequence of data structures which are connected together via links.

Link − Each Link of a linked list can store a data called an element.

Next − Each Link of a linked list contain a link to next link called Next.

LinkedList − A LinkedList contains the connection link to the first Link called First.

Linked list can be visualized as a chain of nodes, where every node points to the next node.

126

Data Structure - Linked List

As per above shown illustration, following are the important points to be considered.

LinkedList contains an link element called first.

Each Link carries a data field(s) and a Link Field called next.

Each Link is linked with its next link using its next link.

Last Link carries a Link as null to mark the end of the list

127

Types of Linked List

Simple Linked List − Item Navigation is forward only.

Doubly Linked List − Items can be navigated forward and backward way.

Circular Linked List − Last item contains link of the first element as next and and first element has link to last element as prev.

128

Basic Operations

Insertion − add an element at the beginning of the list.

Deletion − delete an element at the beginning of the list.

Display − displaying complete list.

Search − search an element using given key.

Delete − delete an element using given key.

129

Insertion Operation 130

Deletion Operation 131

Reverse Operation 132

Data Structure - Doubly Linked List

Doubly Linked List is a variation of Linked list in which navigation is possible in both ways either forward and backward easily as compared to Single Linked List

Doubly LinkedList contains an link element called first and last.

Each Link carries a data field(s) and a Link Field called next.

Each Link is linked with its next link using its next link.

Each Link is linked with its previous link using its prev link.

Last Link carries a Link as null to mark the end of the list.

133

Singly Linked List as Circular

In singly linked list, the next pointer of the last node points to the first node.

134

Doubly Linked List as Circular

n doubly linked list, the next pointer of the last node points to the first node and the previous pointer of the first node points to the last node making the circular in both directions.

135

Dynamic Linked Lists

Problem StatementConsider Students Database program, it appears that the program uses (realloc) whenadding or deleting student member. Using (realloc) may solve the problem, especially ifthe structure size and the number of records are small.Actually (realloc) function1. Creates a new buffer with the new size2. Copies the original contents3. Deletes the original buffer4. Returns the address of the new bufferConsider a complicated SStudent structure containing all student information and his coursesdegrees as shown below:

136

Dynamic Linked Lists Contn. 137

Above structure size is 8548 byte, if it is required to build a

program that supports up to

10,000 student. This means adding extra student will cost

transfering following data size

inside the computer:

10000 * 8548 = 85,480,000 Byte

If it is required to transfere 1 byte 1 micosecond the above

addition operation will take 85

second or 1.5 minute. This time is very long.

Understanding the Solution

Another techniqe is used, it depends on storing student information in a separte buffers andlinking between them using a pointers. This techniqe called the Linked List method.Assument the new structure SStudent after adding the member (SStudent*pNextStudent). pNextStudent is a pointer containing the address of the nextmember of the list. Last member of the last have equals pNextStudent NULL.

138

139

Write the Program 140

At the beginning of the program only it is required to have one empty pointer, indicating thatthere is no students added.

141

142

To delete certain record to the list: 143

144

ViewStudents function: 145

DeleteAll function: 146

Stack Implementation withLinked List

147

Stack Implementation withLinked List

148

Stack Implementation withLinked List

149

Stack Implementation withLinked List

150

Stack Implementation withLinked List

151

Stack Implementation withLinked List

152

Queue Implementation withLinked List

153

Queue Implementation withLinked List

154

Queue Implementation withLinked List

155

Queue Implementation withLinked List

156

Queue Implementation withLinked List

157

Queue Implementation withLinked List

158

Queue Implementation withLinked List

159

Queue Implementation withLinked List

160

Queue Implementation withLinked List

161

Queue Implementation withLinked List

162

Queue Implementation withLinked List

163

Queue Implementation withLinked List

164

Queue Implementation withLinked List

165

Queue Implementation withLinked List

166

Queue Implementation withLinked List

167

Queue Implementation withLinked List

168

Queue Implementation withLinked List

169

Doubly-Linked List

170

Doubly-Linked List 171

Doubly-Linked List 172Node contains:

key

next pointer

prev pointer

Doubly-Linked List 173

Doubly-Linked List 174

Doubly-Linked List 175

Doubly-Linked List 176

177

References 178

http://www.tutorialspoint.com/data_structures_algorithms/index.htm

http://www.studytonight.com/data-structures/

std::printf, std::fprintf, std::sprintf, std::snprintf…..

C Programming for Engineers, Dr. Mohamed Sobh

C programming expert.

fresh2refresh.com/c-programming

C programming Interview questions and answers

C – Preprocessor directives