0% found this document useful (0 votes)
292 views48 pages

Embedded C Ppts

The document provides an introduction to embedded C programming. It discusses key differences between C and embedded C, including limited resources in embedded systems. It outlines the basic steps to write an embedded C program: writing source code, compiling for errors, removing errors, generating a hex file, and burning the code onto a microcontroller. An example "Hello World" embedded C program is also provided.

Uploaded by

Kapil Garg
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
292 views48 pages

Embedded C Ppts

The document provides an introduction to embedded C programming. It discusses key differences between C and embedded C, including limited resources in embedded systems. It outlines the basic steps to write an embedded C program: writing source code, compiling for errors, removing errors, generating a hex file, and burning the code onto a microcontroller. An example "Hello World" embedded C program is also provided.

Uploaded by

Kapil Garg
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 48

A venture of KC Robotics & Embedded Pvt. Ltd.

A Quick Introduction to Embedded C Programming

1/17/2012

www.thinnkware.com

A venture of KC Robotics & Embedded Pvt. Ltd.

C VS EMBEDDED C
1. 2. C is for desktop computers, but embedded C usually is for microcontroller based applications. C use the resources of desktop computers (memory, OS, etc), but Embedded C use only limited resources available in chip (limited RAM, ROM, ports, etc). Embedded C could be a subset of C. Usually in C what we develop would have headers like stdio.h, using which the system yields a output file feasible to that particular OS(windows, Linux etc), but when it comes to embedded C, everything is same except, you will get an output file which could be directly loaded in to the microcontroller. In C the output is an executable file, but in embedded C the output is a hexadecimal file. Libraries and headers used in C are different from that of Embedded C because the libraries used in embedded C differ in case of different microcontrollers.
www.thinnkware.com 2

3.

4. 5.

1/17/2012

A venture of KC Robotics & Embedded Pvt. Ltd.

WRITING YOUR FIRST C PROGRAM:


1. 2. 3. 4. 5. Write text of program (source code) using an editor. Run the compiler to check for errors and warnings in the edited Errors must be removed from the program to make it run successfully use the convenience of creating hex using the compiler from the executable file Burn the code on the microcontroller and check the output.

1/17/2012

www.thinnkware.com

A venture of KC Robotics & Embedded Pvt. Ltd.

EXAMPLE OF C PROGRAM
/* This is my first C program */ #include <reg52.h> int main() { return 0; }

// Header file to be included. // Starting MAIN. // opening Brace. // Closing Brace.

1/17/2012

www.thinnkware.com

A venture of KC Robotics & Embedded Pvt. Ltd.

UNDERSTANDING C SYNTAX
All the syntaxes have been defined in C when it was developed. Syntaxes are to be followed very strictly while writing C program as they as the major source of error while compiling any C code. Each language has a syntax and semantics to work on and write programs in it. These syntax are checked by the compiler in the highest possible way so that at run time there should not b any issues in the program. A .c file is called a module. Many programs are composed of several .c files and libraries that are linked together during the compile process to create a single executable file.

1/17/2012

www.thinnkware.com

A venture of KC Robotics & Embedded Pvt. Ltd.

RESERVED WORDS IN C
1. C programs are constructed from a set of reserved words which provide control and from libraries which perform special functions. The basic instructions are built up using a reserved set of words, such as main, for, if, while, default, double, extern, for, and int, to name just a few. 2. You cannot use default, for example, as the name of a variable. An attempt to do so will result in a compilation error. 3. If you use a word which has already been adopted in a library, there will be a conflict between your choice and the library.

1/17/2012

www.thinnkware.com

A venture of KC Robotics & Embedded Pvt. Ltd.

STRUCTURE OF C PROGRAM
The form of an ideal embedded C program should be: 1. Preprocessor commands. 2. Functions. 3. Declarations 4. Variables 5. Statements

1/17/2012

www.thinnkware.com

A venture of KC Robotics & Embedded Pvt. Ltd.

VARIABLES IN C
1. While making codes we need to store some values which keeps on varying from the beginning to the end of the execution of code. Depending on these values various decisions can be taken to change the execution flow. These varying quantities are known as variables. 2. The name of these variables are actually what we call as declaration. The names given to these variables must not be a reserved word of C libraries. 3. It will cause an error if you keep the same name for a variable and reserved word.

1/17/2012

www.thinnkware.com

A venture of KC Robotics & Embedded Pvt. Ltd.

DECLARATION AND DEFINITION


These two words have different meaning in embedded C. Usually people use them interchangeably. Declaration: It is just writing the name of a variable to be used in the program. No memory has been assigned to the variable till declaration. For e.g.: int x. Definition: Giving a value to this variable that has been declared earlier is known as definition. After definition the memory space is allocated to the variable. For e.g.: x = 10. Declaration and definition: They both can be done together in a single line. For e.g.: int x = 10. Here also memory space will be allocated to the variable.

1/17/2012

www.thinnkware.com

A venture of KC Robotics & Embedded Pvt. Ltd.

THE COMPILATION PROCESS

1/17/2012

www.thinnkware.com

10

A venture of KC Robotics & Embedded Pvt. Ltd.

CONCEPT OF HEADER FILES


Usually header files used in C are stdio and conio, but here in embedded C while working on microcontrollers the header files are not defined. They vary as per the use of microcontroller. For e.g.: the header file used while programming for AT89S52 is reg52.h. Header files have important functions in them which are used throughout the program to used pins and ports the microcontrollers and many other things. During compilation while checking for errors and warnings, the content of the header files are copied and are pasted into the main C program. We can not see it but it actually works in this way. This is how the functions written inside the header files are now included into the main C program. That is the reason why we always write as #include<reg52.h>

1/17/2012

www.thinnkware.com

11

A venture of KC Robotics & Embedded Pvt. Ltd.

SCOPE : LOCAL
Local These variables only exist inside the specific function that creates them. They are unknown to other functions and to the main program. As such, they are normally implemented using a stack. Local variables cease to exist once the function that created them is completed. They are recreated each time a function is executed or called. They are declared and defined in the function only. For e.g.: int main() { int x, x = 10; x++; } Here x is a local variable which is local to main function. Any function outside main cannot access this x variable.
1/17/2012 www.thinnkware.com 12

A venture of KC Robotics & Embedded Pvt. Ltd.

SCOPE : GLOBAL
Global These variables can be accessed (i.e. known) by any function comprising the program. They are implemented by associating memory locations with variable names. They do not get recreated if the function is recalled. They are declared and defined out of every function. They are also like preprocessor variables. They are defined outside of main and other functions. int y = 10; int main() { int x = 11; x++; y++; } Here y is a global variable and x is a local variable. Y has been declared and defined outside any function and hence can be used any where in the program as shown here in main.
1/17/2012 www.thinnkware.com 13

A venture of KC Robotics & Embedded Pvt. Ltd.

SCOPE OF OPERATORS AND VARIABLES


C is a block structured language. Blocks are delimited by { and }. Every variable defined has a limit or area in which the variable is valid in the code. Blocks can be defined wherever a C statement could be used. int main { int a = 5; printf("\n%d", a); { int a = 2; printf("\n%d", a); } return 0; } Here a = 5 is valid throughout the program, but a = 2 is valid only in the inner opening and closing brace. Hence the first printf will print 5 and second prntf will print 2 as the variable in closest proximity of local brace will be given priority.
1/17/2012 www.thinnkware.com 14

A venture of KC Robotics & Embedded Pvt. Ltd.

VARIABLE STORAGE CLASS


The variable a = 5, can be used between anywhere in between its delimiting braces. Hence several scopes and types of variables are used as per the application needed. These are known as VARIABLE STORAGE CLASS. Other storage classes are: 1) Auto : The default class. Automatic variables are local to their block. Their storage space is reclaimed on exit from the block. 2) Register : These are variables which have the scope of an auto variable but are stored in a different memory to have faster access for use and change of variable. Use of the register class is not recommended, as the compiler should be able to make better judgment about which variables to hold in registers. 3) static : On exit from block, static variables are not reclaimed. Their specialty is that they retain their value even after the braces have been executed. For e.g.: static y = 5. 4) extern: : These are the variables which are declared in a different file and are used in another C files. External variables are defined outside of any function. For e.g.: extern x = 5.
1/17/2012 www.thinnkware.com 15

A venture of KC Robotics & Embedded Pvt. Ltd.

DATA TYPES IN C
The most basic concept that is used in C programming is Data Types. The variables are the most used and important part of a C code, as they hold data based upon which decisions can be taken. But a limitation comes in size of the variable as some dont have memory size large enough to hold a big value or vice versa. This size of the variable for any variable is actually told by the Data type of the variable. Data type is written with the declaration. There are different data types in C. Different data types, their size and value range that can be stored in them is mentioned here.
Name char int float double
1/17/2012

Description character integer Floating point Double precision floating point

Size 1 byte *2 bytes 4bytes 8bytes


www.thinnkware.com

Range unsigned: 0 -255 unsigned:0-65535 +/- 3.4e +/- 38 (~7 digits) +/- 1.7e +/- 308 (~15 digits)
16

A venture of KC Robotics & Embedded Pvt. Ltd.

THE BASICS OF THE C PROGRAM


Constants and Variables Operators: +, -, *, /, %, &, !, ^, |, ? : Expressions Statements
float a = 1.5, b = a + 3.1 ; or float b = a + 3.1, a = 1.5 ; main( ) { int i ; printf ( "Enter value of i " ) ; scanf ( "%d", &i ) ; if ( i == 5 ) printf ( "You entered 5" ) ; else printf ( "You entered something other than 5" ) ; }
www.thinnkware.com 17

int a, b, c, d ; a = b = c = 10 ; or int a = b = c = d = 10 ;

1/17/2012

A venture of KC Robotics & Embedded Pvt. Ltd.

RELATIONAL AND LOGICAL OPERATORS


The following relational operators produce a true or false value. Operator Meaning > greater than >= greater than OR equal to < less than <= less than OR equal to == equal != not equal The following logical operators are used to combine logical values. && AND || OR ! NOT
1/17/2012 18

www.thinnkware.com

A venture of KC Robotics & Embedded Pvt. Ltd.

INCREMENT AND DECREMENT OPERATORS


These are of two types: Increment and decrement. i++ post increment operator. i-- post decrement operator. ++i pre increment. --i pre decrement. In post method, the value of variable is incremented or decremented after the execution of this statement. In pre method, the value of variable is incremented or decremented before the execution of this statement.

1/17/2012

www.thinnkware.com

19

A venture of KC Robotics & Embedded Pvt. Ltd.

ORDER AND PRECEDENCE OF OPERATORS


Operator precedence describes the order in which C reads expressions. Lets evaluate this expression: a=4+b*2; Operators higher in the chart have a higher precedence, meaning that the C compiler evaluates them first. Operators on the same line in the chart have the same precedence, and the "Associativity" column on the right gives their evaluation order.

1/17/2012

www.thinnkware.com

20

A venture of KC Robotics & Embedded Pvt. Ltd.

ORDER AND PRECEDENCE OF OPERATORS


Operator type Primary expression operator Unary operator Binary operator Ternary Operator Assignment Operators Comma Operator ) [] . -> expr++ expr-* & + - ! ~ ++expr -expr (typecast) sizeof Associativity left-to-right right-to-left

* / % + - >> << < > <= left-to-right >= == != & ^ | && || ?: = += -= *= /= %= >>= <<= &= ^= |= , right-to-left right-to-left left-to-right

1/17/2012

www.thinnkware.com

21

A venture of KC Robotics & Embedded Pvt. Ltd.

LOOPS AND CONDITIONAL STATEMENTS


Loops are most important part of C coding when making logic using different values of variables. Depending on the values of variables the flow of execution can be changed using these loops. Loops are also known as conditional statements as they work on certain values of the variables as selected by the user. Different types of loops have been implemented in C. They are: if, if-else, if-else ladder, while, do-while, for. Different loops have different syntax to implement in C code. The loops work on TRUE and FALSE conditions i.e. if the condition for the variable is true, the loop will execute and if the condition is false the loop will break.

1/17/2012

www.thinnkware.com

22

A venture of KC Robotics & Embedded Pvt. Ltd.

if-else CONDITIONAL STATEMENT


The IF statement checks for conditional execution of c-codes i.e. if the condition for the if block proves to be true, then statements within the if block get executed otherwise statements within else block get executed. int main( ) If loop syntax and example: { int num ; The syntax is as follows: printf ( "Enter a number less than 10 " ) ; scanf ( "%d", &num ) ; /* if evaluated expression is not 0 */ if ( num <= 10 ) if (expression) { { printf ( Thinnkware" ) ; /* then execute this block */ } } else else { { /* otherwise execute this block */ printf(Hello) } } return 0; }
1/17/2012 www.thinnkware.com

23

A venture of KC Robotics & Embedded Pvt. Ltd.

ITERATING LOOP CONTROL STATEMENTS


while ( condition) { statement; / } do { statement; } while ( condition); /* while expression is true do*/ * statement*/

/* statement */ /* while expression is true*/

for (initialization; condition; increment/decrement) { Statement; /* till condition doesnt go false*/ }


1/17/2012 www.thinnkware.com 24

A venture of KC Robotics & Embedded Pvt. Ltd.

WHILE EXAMPLE int main( ) { int i = 1 , j = 1 ; while ( i++ <= 100 { while ( j++ <= 200 ) { printf ( "%d %d\n", i, j ); }} return 0; }

FOR EXAPMLE int main( ) { int i, j ; for ( i = 1 ; i <= 10 ; i++ ) { printf ( "\n%d %d\n", i, j ) ; } return 0; }

The difference between the while and the do-while loops is the location of the test. With a while loop the test is made before the statement that forms the body of the loop is executed; it is possible that the statement is never executed. With the dowhile loop, the statement will always be executed at least once; the value of the expression then determines if the statement is executed again.
1/17/2012 www.thinnkware.com 25

A venture of KC Robotics & Embedded Pvt. Ltd.

SWITCH STATEMENTS: Switch statements can be used in place of conditional if statement. BREAK AND CONTINUE STATEMENTS: break statement helps the program to control branch out of the switch statement. continue statements can only be used in loop statements to skip executing statements after the continue statements for the iteration for which such conditions are implied in a c-program. GOTO STATEMENTS:
goto makes the c-program unstructured. goto can help the program control to branch from one program section to anywhere within the program.

1/17/2012

www.thinnkware.com

26

A venture of KC Robotics & Embedded Pvt. Ltd. GOTO STATEMENT EXAMPLE int main( ) { int goals ; printf ( "Enter the number of goals scored); scanf ( "%d", &goals ) ; if ( goals <= 5 ) goto sos ; else { printf ( "About time soccer players learnt C\n" ) ; printf ( "and said goodbye! adieu! to soccer" ) ; exit( ) ; /* terminates program execution */ } sos : printf ( "To err is human!" ) ; return 0; }
www.thinnkware.com 27

SWITCH CASE EXAMPLE int main( ) { int i = ; scanf ( "%d", &i ); switch (i) { case 1 : printf ( "I am in case 1 \n" ) ; break; case 2 : printf ( "I am in case 2 \n" ) ; case 3 : printf ( "I am in case 3 \n" ) ; default : printf ( "I am in default \n" ) ; } return 0; }
1/17/2012

A venture of KC Robotics & Embedded Pvt. Ltd.

BREAK EXAMPLE int main( ) { int i = 1 , j = 1 ; while ( i ++<= 100 { while ( j++<= 200 ) { if ( j == 150 ) break ; else printf ( "%d %d\n", i, j ); } return 0; }
1/17/2012

CONTINUE EXAMPLE int main( ) { int i, j ; for ( i = 1 ; i <= 2 ; i++ ) { for ( j = 1 ; j <= 2 ; j++ ) { if ( i == j ) continue ; printf ( "\n%d %d\n", i, j ) ; } } return 0; }

www.thinnkware.com

28

A venture of KC Robotics & Embedded Pvt. Ltd.

FUNCTION: C-CODING BUILDING BLOCKS


A function is a self-contained block of statements that perform a coherent task of some kind. A Function is a series of instructions to run. A function may Return a value or may not return a value. A calling function may pass arguments to the called function or may not pass arguments to the called function. C program is a collection of one or more functions. A function gets called when the function name is followed by a semicolon. A function is defined when function name is followed by a pair of braces in which one or more statements may be present. Any function can be called from any other function. Even main( ) can be called from other functions. A function can be called any number of times. The order in which the functions are defined in a program and the order in which they get called need not necessarily be same. A function can be called from other function, but a function cannot be defined in another function.
1/17/2012 www.thinnkware.com 29

A venture of KC Robotics & Embedded Pvt. Ltd.

FUNCTION: CALLING, ARGUMENTS


Now as the code has been divided into functions, they need to be synchronized. This is done by function calling. Whenever the code needs to execute a section, that specific function will be called. A calling function may pass arguments to the called function or may not pass arguments to the called function. Arguments are like input variables which can used to compute the execution of the function. But there is also a overhead while making function calls. The execution of the program jumps form the place of function call to the place of function definition. That waste the time of the microcontroller. A lot of function jumping is also hazardous to the execution time of the code. The solution to this type of waste is the use of Macros in the program. But macros should be used in place of small function usually single line function only because with macros the code size increases. Macros are discussed later.

1/17/2012

www.thinnkware.com

30

A venture of KC Robotics & Embedded Pvt. Ltd.

FUNCTIONS
The ANSI C style of declaring and defining a function is: Return_type Function_name (parameters list) { statements.. /*Function definition*/ } A function definition is where the function name, parameters, code and return type are specified. A function declaration is where the name and return type of a function are given. The definition of a function includes a declaration of that same function implicitly. A function can be declared many times (as long as the declarations declare the function to be of the same type) but can only be defined once. Declarations of functions are sometimes necessary to appease the compiler, which always assumes, if the information is not available, that all functions return int.
1/17/2012 31

www.thinnkware.com

A venture of KC Robotics & Embedded Pvt. Ltd.

FUNCTIONS
The ANSI C standard introduces function prototypes. An example is given below. It also allows function definitions to be written in the same form as the new prototypes. For e.g: double minimum(double, double); /* prototype of minimum() */ int main() { printf("%f\n", minimum(1.23, 4.56)); /*Function called*/ return 0; } double minimum(double x, double y) /* definition of minimum() */ { if (x < y) return x; else return y; }
1/17/2012 www.thinnkware.com 32

A venture of KC Robotics & Embedded Pvt. Ltd.

MACROS
Macros can be a useful way to customize our interface to C and make our code easier to read and less redundant. Macros are used to define constants. Macros can be used to improve code readability. They work at the time of preprocessing in compilation stages. Prior to compilation of the code, it replaces the name of the macros with the values defined for the respective names. For e.g: #define PI 3.14159 They are globally declared. So, when compiler works it searches the word PI in the whole code and replaces that word with 3.14159. Macros are faster in processing. Complex equations can also be defined as macros.

1/17/2012

www.thinnkware.com

33

A venture of KC Robotics & Embedded Pvt. Ltd.

MACROS
Examples of macros: #define SQ(x) ( (x) * (x) ) #define MIN(x,y) ( ((x) < (y)) ? (x) : (y) ) In effect you can write often used simple functions as a macro rather than a function, the advantage is speed (there is no function call overhead) and no type definition is necessary (it can be reused for ints, doubles, floats etc.). The disadvantages are that if you use the macro several times, then the code will appear in your program several times, and there can be side effects caused by not creating new copies of the parameters (which is what happens when a function is called). When defining a macro there cannot be any spaces between the macro name and the parameter list; when calling a macro no such restriction holds. A general mistake which is made while defining functions in macros is not using brackets. For e.g: #define square(a+b) a+b * a+b This will be interpreted as a+(b*a)+b So make sure to put brackets at correct places as #define square(a+b) (a+b) * (a+b)
1/17/2012 www.thinnkware.com 34

A venture of KC Robotics & Embedded Pvt. Ltd.

POINTERS IN C
Pointers are special kind of variables used in c to store addresses of another variable. Pointers are made to access the variables by their addresses rather than their name. Pointers are actually data-types which points to another variable of same data type. The * and & Operators : & : gives the address of something in memory, that is it generates a pointer to the object. * : gives what is pointed at by a pointer (called dereferencing). For e.g: int i = 0 , *j; j = &i; Here pointer j is pointing to the variable i. That means j holds the address of i. j = memory address of variable i. *j = integer value of variable i.
1/17/2012 www.thinnkware.com 35

A venture of KC Robotics & Embedded Pvt. Ltd.

POINTERS ARITHMETIC
Pointer arithmetic is same as that of a variable. For e.g: *j = *i + *j; *a = *a/ *b; (a = *a+ b This gives an error). char * p, s[100]; int * a, b[100]; double * f, g[100]; p = s; /* p points to s[0] */ a = b; /* a points to b[0] */ f = g; /* f points to g[0] */ p++; /* p points to s[1] */ a++; /* a points to b[1] */ f++; /* f points to g[1] */ The size of a pointer is always 4 bytes irrespective of the data type it is pointing to. This is because pointer holds the address of the variable not the value of it.
1/17/2012 www.thinnkware.com 36

A venture of KC Robotics & Embedded Pvt. Ltd.

Typecasting
This is a method which is used to change the data type of a variable to another data type. For e.g: int i = 0; char c = c; i = (int) c; Here the data type of the character is changed into integer. The character c is stored into integer i. Thus its actually the ASCII value of c that is stored into integer i. An integer can also be stored in a character. But size of an integer is 2 bytes and size of a character is 1 byte. Hence while storing an integer into a character, data gets lost because character cant store an integer of 2 bytes. Similarly pointer datatype can also be changed like this. For e.g: int* i, char* j; j = (int*) i;
1/17/2012 www.thinnkware.com 37

A venture of KC Robotics & Embedded Pvt. Ltd.

NULL* AND VOID *


VOID *: This is also a type of pointer which has no data type. Void means empty hence the data type of this pointer is not defined. This means that this pointer is not pointing to any variable of any data type. To use such a pointer we have to type cast it into the variables data type to whom we want it to point to. We cant operate arithmetic or logical operation on this kind of pointer. NULL *: The constant 0 when used in a pointer context (e.g. assigned to a variable of any pointer type or compared with a pointer value) is replaced by a null pointer of the appropriate type. Such a pointer is used to indicate that a pointer does not point anywhere or is invalid. The preprocessor constant NULL can be used instead of the constant 0. Library functions that return pointers return NULL if an error occurs. The value of a pointer should always be checked to ensure that it is not NULL before attempting to dereference it. Attempting to dereference a NULL pointer will give a run-time error on some systems.
1/17/2012 www.thinnkware.com 38

A venture of KC Robotics & Embedded Pvt. Ltd.

DERIVED DATA TYPES: Arrays


Arrays are an example of derived data types. Arrays holds several variables of same data type. Mentioning the size of the array is important. The array terminates with a null \0 at the end. Size of an array = no. of variables + 1(for null). The variables in an array are indexed. The first variable is given the index 0 and it increments as the no of variables increases. For e.g. int arr[4] : means it is an array which holds 4 variables of integer data type + null character. Null character is not visible to the user. Even there is no need to put a null character when defining an array. The compiler automatically puts it before closing brace of the array.

1/17/2012

www.thinnkware.com

39

A venture of KC Robotics & Embedded Pvt. Ltd.

DERIVED DATA TYPES: Arrays


int arr[] = {1,2,3,4,5,6}: in such a case of declaration and definition together we dont need to declare the size of the array. In later case first variable i.e. 1 is at index 0, 2 is at index 1 and increments for the rest of the array. Here arr is the name of the array and also arr holds the base address of the array i.e. the address of the first variable of the array. The array holds contiguous address spaces in memory starting from index 0 to the end.

1/17/2012

www.thinnkware.com

40

A venture of KC Robotics & Embedded Pvt. Ltd.

DERIVED DATA TYPES: Strings


String is also a derived data type. String is an array of characters terminated by a null character. It is actually a pointer which points to a character which is written in the enclosed quotes. For e.g : char* str = Thinnkware Here str is a character pointer which is pointing to first character i.e T enclosed in quotes. If we do str++, then str will start pointing to h i.e. second character of the word enclosed in quotes. Lets take an example: char* abc = Thinnkware welcomes you; Here *abc = T, If abc++ is written then, *abc = h. And it keeps on incrementing so on with the address. The strings also ends with a terminating null character.
1/17/2012 www.thinnkware.com 41

A venture of KC Robotics & Embedded Pvt. Ltd.

DYNAMIC MEMORY ALLOCATIONS


Till now what we talking about in the difference between declaration and definition is about the memory space occupied. That memory space is actually static memory. This memory is used when we define variables or any other data while writing the program. After compilation the memory space is allocated to the required members from the static memory. These are the cases where we know the amount of size to be allocated to a variable or array or any member. Here is a pictorial representation of static memory. The variables are saved in them as soon as they are defined and also are fetched from the same segments when needed in the program.

1/17/2012

www.thinnkware.com

42

A venture of KC Robotics & Embedded Pvt. Ltd.

DYNAMIC MEMORY ALLOCATIONS


This is a method which is used to allocate memory to any variable or derived data type at run-time i.e. the time when the code is executing. There are 3 methods or functions to allocate memory dynamically: 1) Malloc() 2) Calloc() 3) Realloc() Malloc() and calloc() are used to allocate new memory whereas realloc is used to allocate the free memory which has been allocated earlier. Mostly malloc() and calloc() are used. These functions work on pointer theory.

1/17/2012

www.thinnkware.com

43

A venture of KC Robotics & Embedded Pvt. Ltd.

MALLOC
Malloc: The memory allocated using this method may be contiguous may not be contiguous. The memory allocated has garbage values. For e.g: id we have to allocate a memory of 6 integers, int* memory; memory = (int *) malloc (6 * sizeof (int) ); Here to store 20 integers, typecasting is used before malloc because malloc returns void*. So we have to typecast it to the pointer data type that we have to store. In case of malloc the memory assigned to malloc in non contiguous form the memory pointer points to the first address of the memory space. This memory space then points to the next memory address allocated to the malloc. In this way it keeps a track of the individual elements of the array. A pictorial representation gives you a clear idea.

1/17/2012

www.thinnkware.com

44

A venture of KC Robotics & Embedded Pvt. Ltd.

MALLOC

1/17/2012

www.thinnkware.com

45

A venture of KC Robotics & Embedded Pvt. Ltd.

CALLOC
Calloc: The memory allocated using this method is always contiguous. The memory allocated is initialized with value 0. Thats why calloc() is faster as compared to malloc(). For e.g: If we have to store 6 integers, int * memory; memory = (int*) calloc (6, sizeof ( int) );

1/17/2012

www.thinnkware.com

46

A venture of KC Robotics & Embedded Pvt. Ltd.

FREE
Free: It is the method to free the memory allocated using malloc() or calloc(), so that the memory can be used further for allocation. For e.g: Free (memory); It will free the memory allocated during previous malloc() or calloc() operations.

1/17/2012

www.thinnkware.com

47

A venture of KC Robotics & Embedded Pvt. Ltd.

Embedded C Coding Guidelines


The most important part after successful coding is its documentation. Documentation is needed for code readability. Documentation or comment lines begin with a double slash ( // ) and all text to the end of the line is considered a comment. Documentation should appear : before the main program (program header) before each function (function header) before or next to lines of code within a function (line comments) For e.g.: int add(int x, int y); // Function to add 2 numbers The next important part of C coding is the name conventions used. Names should be meaningful in the application domain, not the implementation domain. Note that well-structured code is layered internally, so your implementation domain is also the application domain for lower levels. For e.g.: int AdditionOfNumbers(int FirstNumber, int SecondNumber);

1/17/2012

www.thinnkware.com

48

You might also like