Friday, November 14, 2014

Volatile : Demistyfied


  

Introduction
"Volatile" is a qualifier in 'C' which is applied to a variable when it is declared. So, what does it tells to the compiler? It gives the information to the compiler that the value of the variable may change at any time during the execution of the code without the knowledge of the compiler. If proper precautions are not taken, we might not get the desired results. A variable should be declared volatile whenever its value could change unexpectedly.


The syntax for declaring the variable as volatile is given below,
volatile dataTpye variable;  

Let us understand the “Volatile” keyword in deep through the following examples.


Example 1:
Let us consider small and simple example as shown in the Fig:1 to study the behavior of the 'volatile' keyword in C.

Fig 1: Code without the use of volatile.
In the above example the intention of the programmer is to keep polling inside the while loop until 'flag' value becomes 1(one).But the compiler, while compiling the code applies the optimization techniques and compiler will notice that no other code can possibly change the value stored in 'flag', and therefore assume that it will remain equal to 0(Zero) all times. The compiler will then replace the function body with an infinite loop as shown in the below Fig 2

                Fig 2: Optimization applied by the compiler to the code shown in fig1.

Let we check the size of the assembly code generated by the compiler as shown in the below Fig 3.

Fig 3: Size of assembly code generated by the compiler.


Now, if you observe Fig 3, the size can be found as 482 bytes in the 5th column. Now, we will apply the volatile keyword to the flag variable to the code shown in Fig 1, as shown in the below Fig 4,

                 Fig 4: Code with volatile  
Let we check the size of the assembly code generated by the compiler as shown in the below Fig 5.
Fig5: Size of assembly code generated by the compiler after applying 'volatile' keyword.


Now, if you observe Fig 5, the size can be found as 501 bytes in the 5th column. So, when we compare the sizes of both the codes with & without volatile keyword, obviously one can observe that the compiler is not optimizing the variable flag when it is qualified as “Volatile”.

Let we still experiment further to explore where the compiler is optimizing the code, to do this apply the vimdiff command to the assembly codes generated earlier, the difference is shown in the below fig 6:


Fig 6: Difference between the assemblies codes generated without & with volatile keyword.
From the above figure, we can conclude that volatile keyword prevents the application of optimization techniques by the compiler.

Example 2
Let us consider another example, where “for” loops are used commonly in the Embedded C code for the generation of the delays. Let us see how the compiler will optimize the code containing the “for” loops in the embedded C code without the use of the qualifier “Volatile” as shown in the Fig 7 below,

Fig7: For loop without volatile qualifier.
Let us generate the assembly code for the above given example, using the command given in the note 2, and getting the size of the assembly code using the “ls” command is given below in Fig 8,

Fig8: Size of assembly code generated by the compiler without volatile qualifier.
Now, we will apply the volatile keyword to the “i” variable in the code shown in Fig 7, as shown in the below Fig 9,

Fig9: Code with volatile keyword.
Let us generate the assembly code for the above given example, using the command given in the note 2, and getting the size of the assembly code using the “ls” command is given below in Fig 10,

Fig10: Size of assembly code generated by the compiler with volatile qualifier.
Comparing the sizes in the Fig 8 & 10, one can identify the compiler is applying the optimization techniques without the volatile qualifier. The dis-assembly code for both with & without volatile keyword is shown below in Fig  11,

Fig 11: Difference between the assemblies codes generated without & with volatile keyword.
Example 3 : Global variables accessed by multiple tasks within a multi-threaded application
Let us consider one more example to show how the global variable will be affected by the compiler optimization in the multi-threaded application. The example code snippet is shown as below in Fig 12,

Fig 12: Demo code to show how global variable will be affected in multi threaded program.
In the above demo program, the compiler doesn't have any knowledge of context switching between the two threads. If the compiler optimizations are turned “ON” then the compiler will assume that global_item_count variable is always “ZERO” and no other part of the thread is attempting to modify it. So, the compiler may replace the line no. 11 in the demo code like this

 
Which is nothing but the infinite loop, so in-order to avoid such optimizations by the compiler, it is safe to declare the variable global_item_count as “volatile”.

Similarly, one can realize the effect of producer-consumer problem accessing the global variable without declaring it as “Volatile”. Refer the link below


Example 4: Interrupt service routines
Let us consider another example given in the fig 13, where “volatile” plays a very important role in the ISR.
Fig 13: Volatile keyword used in ISRs


In the above example, if the flag is not declared as “Volatile” , then the compiler may optimize the code assuming always the flag is ZERO and replace the while(!flag) to while(TRUE) in line no.11, which is nothing but infinite loop. But the flag value will change when the interrupt occurs.

Whether to declare the variable as 'Volatile' or not is cross compiler dependent, anyhow it is good practice to declare the variable as 'Volatile' to achieve the portability of the code.

Conclusion:
The main use of volatile keyword is to prevent compiler from optimizing the code in terms of time complexity by generating a code that uses CPU registers as faster ways to represent variables. By declaring the variable as “Volatile” forces compiled code to access the exact memory location in RAM on every access to the variable to get the latest value of it which may have been changed by another entity.

A variable should be declared volatile whenever its value could change unexpectedly. In real time, three types of variables could change,

1. Memory-mapped peripheral registers

2. Global variables modified by an interrupt service routine

3. Global variables accessed by multiple tasks within a multi-threaded application  


Friday, October 17, 2014

Electronics Rocks 2014


On October 10th, Electronics for you (EFY) hosted their Electronics Rocks conference in NIMHANS Convention Centre, Bangalore. Business conferences give leaders of industry a chance to get together and discuss the changes that are going on in their field. On the first day of the event, Emertxe participated in the event. As we understand the phrase “Connect, Share and Empower ” drew together many of the key themes by delegates. The event was wide ranging and featured a wide array of speakers and attendees from numerous industries.

The Organizers were excited to see 3450 + delegates joined at the conference. It was particularly proud of the attention of their attendees till the end of the session. Many attendees raised their queries and doubts been clarified in a healthy way. Emertxe is one of the community partner of Electronics Rocks and proud to join hands at the conference.

Mr. Jayakumar, Director of Emertxe Information Technologies (P) Ltd presented a good speech at the conference. He focussed on “Design Challenges faced in building products for IOT”. This discussion session was really good and the attendees paid their attention on speakers presentations in conference programs. Mr.Maaz MD of Emertxe was present in the event connecting with various electronics ecosystem partners by sharing his perspectives.

Finally, the Conference closed with a great thinkers panel and once again thanks for all of your wonderful support who made this session a goal oriented. Looking forward to contribute more in similar events by sharing our knowledge and experience. The slide-deck presented at the event is shared below.


Wednesday, July 23, 2014

Emertxe-OSFY: Articles

Our Team from Emertxe consist of subject matter experts in specific areas (ex: Advanced C programming, Linux Kernel, Software Engineering etc..). This blog was initially created to share our knowledge with broader community, which we are expending further.

Open Source For You (OSFY) is India's top magazine on Open Source, promoted by Electronics For You (EFY) media. For the past couple of months we have been publishing our articles, now we have plans to continue publish articles on various topics. Here are the links to download PDF edition of these articles:



Tuesday, May 27, 2014

Split command : Organize your C files better

Often when we walk into car garage, one can observe that the mechanic having different type of spanners, screw drivers for fixing different set of problems. These are nothing but tools that makes life of the mechanic easier. In the similar lines knowing different tools (ex: commands) and using it for their advantage can make life of a developer much easier. In this post let us have a look into split command.

Let us take example of the given file (Fig1, split_file.c), which has the obvious main function and two other functions i.e. function1 and function2. As the size of the file grows, file becomes bigger in size and the development may want to move some of the function implementation into other files and eventually compile them using make utility.

Fig1: split_file.c
One way to split function1 and function2 into two different file is by using the split command. Here is a simple way to understand the split command:
                                                split –b <file> <targetfile>
                                                split –l  <file> <targetfile>

where
                                                file: Input file which you need to get it splitted
                                               targetfile: Instance of output where it needs to be spitted
After executing the split command the command itself will split the output into targetfileaa, targetfileab etc, depending on the type of split. The “-b” or “-l” option talks about if the split to be based on bytes of lines of the file.

In our case since the main, function1 and function2 are having 10 lines each, we can apply a split based on the split as follows (Fig2: Applying split command)

Fig2: Applying split command
After the command you can do ls –al and see there are split_outputaa, split_outputab, split_outputac etc,which will have main, function1 and function2 split into it. Let us see the file contents by executing the cat (Fig3: Cat command for viewing contents) command as follows.
Fig3: Output of split command
In this way larger files can be split into smaller set of files, which come in handy during development. Such tools also help a developer to keep source files compact and split across, thereby helping in maintaining and enhancing them without much problem. For example if you have 5000+ lines of code in a single file, its high time to start dividing them into multiple times. Its time to start splitting! 

Monday, May 19, 2014

Mistake proofing in C programs

The Japanese concept of ‘poka-yoke’ talks about preventing mistakes by introducing certain mechanisms. It was originally designed for machinery which can be applied for any other aspect of life as well. What about mistake proofing in programming, especially with C programs? 

The earlier we get to know about mistakes in programs it is easier to fix them.

Let us consider the following code snippet (Fig 1): 

Fig 1: Simple if condition to check against MAX_VALUE
It is a simple conditional code where integer variable value is compared against absolute value MAX_VALUE and prints appropriate messages. While this appears to be a very simple program many times during development the equal-to operator (‘==’) is mistakenly replaced with assignment (‘=’) operator, which will yield unfavorable results (Fig 2): 


Fig 2: Small mistake giving incorrect results 
In this case message under if condition always will get printed irrespective of value of variable value.

Now how do we prevent this mistake? Very simple, change the way the equal-to operator is used (Fig 3). 



Fig 3: Mistake proofing during compile time
That way if assignment operator is used against an absolute lvalue, appropriate error message is given during compilation phase itself (Fig 4):


Fig 4: Error getting detected in compile time itself
By making such small changes in the code and making it as a programming practice, developers can avoid mistakes during programming which can be called as ‘poka yoke’. There could be many such examples that can be adopted for writing error free programs by getting issues earlier phase of development.

What other mistake proofing mechanisms you can think of? What other facilities that C offers for developers to operate in prevention mode? 

Saturday, May 10, 2014

Pointer Constant & Constant Pointer - Differences

Introduction:
Pointers are always been a complex topic for the newbies into the C programming world. It will be more confusion for the newbies when these 'sharp knives' are used along with some qualifiers like 'const' in C programming. In this blog I want to focus on difference between 'pointer to constant' & 'constant pointer' in order to make the concept very clear.

General Note :
code snippets provided here is tested with GCC compiler [ gcc version 4.8.2 ] running under Linux environment.


Pointer to constant

As the name itself indicates that the value of the variable to which the pointer is pointing is constant in other words a pointer through which one cannot change the value of variable it points is known as a 'pointer to constant'.

Note 1: But these pointers can change the address they 'point to' but cannot change the value at the address they are 'pointing to'.

Declaration

Table-1: showing how to declare 'pointer to constant'



Illustration

Let us consider the code snippet to understand how 'pointer to constant' works,


Fig-1: Illustration example for 'pointer to constant'


In the above example, at line no.12 we are trying to change the value of the variable to which the pointer is 'pointing to', but this is not possible since the value is constant. When the above code is compiled & run, we are getting the output as shown in the below figure.

Fig-2: Output of the code snippet given in Fig-1



Now we will take the same example to show that the 'address' the pointer is containing is not a constant.

Fig-3: Demonstration example to show that the address is not constant.



From the above figure, one can understand that the 'address' where the pointer is containing can be changed but not the value. This can be clearly understood by the pictorial representation given below,



In Brief:

Table-2: Briefing pointer to constant concept




Constant Pointers

A 'constant pointer' is a pointer that cannot change the address it is containing. In other words, we can say that once a constant pointer points to a variable then it cannot point to any other variable. 


Note 2: But these pointers can change the value of the variable they 'point to' but cannot change the address they are 'holding'.

Declaration

Table-3: showing how to declare 'constant pointer'



Illustration

Let us consider the code snippet to understand how 'constant pointer' works,

Fig-7: Illustration example for 'constant pointer'



From the above fig, it is clear that at line no. 14, we tried to change the address of the pointer 'ptr' to some other variable,but according to the concept it is not possible. The output of the above code snippet is given below. Similarly, one can observe at line no. 12, we are trying to change the value of the variable it is 'pointing to' which is possible.

Fig-8: Output of the code snippet given in Fig-7



This can be clearly understood by the pictorial representation given below,


In Brief:
Table-4: Briefing 'constant pointer' concept



Similarly, we can have both pointer to constant & constant pointer in a single statement. This is left as an exercise to analyze.

Application

We can find 'n' number of applications of these concepts in 'C' as well as 'Embedded C' Programming world. One such simple application of 'pointer to constant' is to find the string length of the given string without any attempt to modify the original string as shown in Example 1 and Example 2 gives an idea of usage of 'pointer to constant' in strcmp() function.

Example1:

Fig-12 : Shows the usage of pointer to constant in strlen() library function.


Example2:

Fig-13 : Shows the usage of pointer to constant in strcmp() library function.

Summary

Table-5



Trick: How to understand the differences between pointer to constant & constant pointers.

Note 3: This trick is for all the newbies for the C programming world , who are confusing with constant & pointers.


From the above summary, separate the part before asterisk(*) & part after the asterisk(*) as given in the below table-6.

Table-6


Enjoy C programming :-)

Tuesday, May 6, 2014

void pointers : Its Genericness

 



Void Pointers : Definition

Void pointers are the pointer variables which has no specific data type. These are also called as Generic pointers because it can point to any data type. In General, the compiler has no idea what type of object a void Pointer really points to.

Void Pointers : Declaration

A void pointer is declared like a normal pointer, using the keyword “void” as the pointer’s type as shown below,

Referencing & De-referencing the void pointers

In order to explain, how void pointers can be referenced & De-reference, let we take a small sample code as shown below in Fig 1,

 Fig 1: Referencing & De-referencing of the void pointers

From the above Fig 1, it is clear that while referencing the void * no need to typecast, only when De-referencing the void *, it need to be type-casted otherwise the gcc compiler will give warning along with error note as shown below in Fig 2,
Fig 2: Result obtained while de-referencing the void pointer without typecasting.
  Fig 3: Output after typecasting the void pointer while dereferencing.

Why void pointers are useful ?

One main advantage of using the void pointers is that it can be 're-usable'. Because of this feature of the void pointers 'space' & 'time' complexities can be reduced to some extent which is very critical in Embedded System designing.
They are very useful when you want a same pointer to point to data of different types at different times.
Let us consider a small simple code snippet, to show how void pointers can be re-usable which reduces the space complexity in the example as shown in the Fig 4 given below,
 

Fig 4: Void pointer reusability.

Fig 5: Output of the code shown in Fig 4.

For more clarity let us understand the above code through pictorial representation.
Line No.14 : The vptr is pointing to the address of the integer variable 'i', as shown below in Fig 6.1
Line No.18 : The vptr is pointing to the address of the character variable 'c', as shown below in Fig 6.2
Line No.22 : The vptr is pointing to the address of the float variable 'f', as shown below in Fig 6.3
Line No.26 : The vptr is pointing to the address of the double variable 'd', as shown below in Fig 6.4

Note : xxxx, yyyy, zzzz, aaaa, bbbb are all some arbitrary addresses shown in the above figures from 6.1 to 6.4.
From the figures 6.1 to 6.4 , it is very clear that we have used only one pointer i.e vptr , instead of four different pointers to point to four different variable of different data types, where space complexity is more. Only one thing that the programmer should keep in the mind while coding is that proper typecasting should be done depending on the different data types.
Void pointers are used in places where you need to work with different pointer types in the same code. One commonly used example is the library function qsort:
base is the address of an array, nmemb is the number of elements in the array, size is the size of each element, and compar is a pointer to a function that compares two elements of the array.

Pointer Arithmetic on Void*

Let us learn how to apply pointer arithmetic on the void pointers through the bug code as shown in the Fig 7 given below.
 

Fig 7: Bug code

Fig 8: Output of the bug code shown in Fig 7

From the above result, one can see that we are not getting the expected output. Surprisingly what went wrong ? Let us analyze the above code & output we got.
1. From the output it is very clear that addresses are incremented by one one byte, this is because the gcc compiler assumes sizeof(void) is 1 byte long.
2. So, when we increment void pointer by one, it is incremented by one byte long as one can observe this from the Fig 8(address part).
3. Now coming to the value part, the first value i.e arr[0] is getting printed correct, but after that all the values are wrong, this I am explaining through the pictorial representation as shown in the Fig 9
to Fig 13 below.
Note : The output depends on the endianness of the architecture.
Fig 9
Fig 10
Fig 11
Fig 12
Fig 13
From the above five figures, we can see why we are not getting the expected output. So the corrected code along with expected output is shown in the Fig 14 & 15 given below,

Fig 14 : Correction to the code given in Fig 7

Fig 15: Expected output for the code given in Fig 11.


void pointers can be assigned to any pointer value. One cannot dereference a void pointer without proper typecasting. Functions such as malloc, calloc, free utilize void pointers.