Showing posts with label Linux. Show all posts
Showing posts with label Linux. Show all posts

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  


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 :-)

Thursday, April 3, 2014

Pit-falls of Bit-fields




In the past few posts we have been checking various aspects related to bit fields. In this blog, let we focus on how bit-lengths will pose a serious issue to achieve portability in case of bit-fields structures.

Portability is basically about having the same program or application running across various processor architecture. When it comes to embedded systems portability plays a very important role as they have diversified set of hardware. 


To start withlet us take a simple program as given below in Fig 1:




Fig 1: Bit-length pose and portability issue. 
 
After running the above code, output is shown in the given below Fig 2:

Note: source code is tested under gcc (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2 version.

 Fig 2: Output of the source code given in Fig 1.

From the above figure 2, it is clear that when we declare the bit-length more than the sizeof(int)[ In our case , it is 4 bytes] , which is compiler dependent we are getting the error at the compile time. The above code perfectly works fine , if the machine WORD size is 64 bits, but fails to work with lower WORD size, which results in portability issue.

Pointers & Bit-fields
I want to focus on one more problem, why pointers cannot be applied for the bit-fields.let me practically explain this problem by taking an example shown in the fig 3 below,

Fig 3: Pointer operation and bit fields

The output of the above source code is given below,


 Fig 4: Output of the source code shown in fig 3.

One can observe from the above fig 4, when tried to reference the bit-field structure variable, compiler is generating an error, this is because direct addressing of the bit-fields structure variables is not possible in C, since the smallest unit of addressable memory in C is a sizeof(char) i.e byte addressable not an bit addressable. This is one of the pit-fall of the bit-field structure in C programming.

From the above two examples, we can conclude that how portability issue is major concern with the bit-fields, and also we saw direct addressing of the bit-fields is not possible in C programming. Apart from this two issues, even sizeof() operator cannot also be applied for the bit-fields since sizeof always returns size in bytes not in terms of bits. Use bit-wise operators instead, they are 100% safe and portable.

Friday, March 28, 2014

Face-off with sizeof()



sizeof : Brief
The unary operator sizeof is used to calculate the size of any datatype, measured in the number of bytes required to represent the type. The result of sizeof is the size of the type of the expression or parenthesized type-specifier that it precedes, and has an unsigned integral type which is usually denoted by size_t ( From Wiki ).
The sizeof() operator behaves differently in comparison with other operators. In this blog let us call out some of the uniqueness of this operator by taking two real time programming examples. The first one is about compile time behavior and second one is during run time behavior.
Case 1: Compile time behavior 
To start with, let us consider the simple code (Fig 1 below):



Fig 1: Sample program to demonstrate the sizeof() operator


Can you guess what would be the output of the above mentioned program? By first look anybody would say it as 4 (Assuming the sizeof(int) is 4 bytes) & 11. But, when I run the program in my system, it is showing 4 & 10 (ref: Fig 2 below)

Fig 2: Output
Why are we getting the value of variable ‘i’ as 10 instead of 11? Here is the reason:
  1. Sizeof operator is the only operator in C, which is evaluated at the compile time. Where sizeof(i++) is replaced the value 4.
  2. One can observe this, shown in the figure given below(inside the box), which contains the assembly code equivalent to the statement in C.



Fig 3: Assembly code generated by the compiler.

Note:
To obtain the assembly code as shown in Fig 3, follow the below given steps.
+ gcc -g filename.c ( In our case sizeof_run.c)
+ objdump -S output_file ( In our case a.out)


From the above figure, one can see that the sizeof() is completely evaluated at the compile time. And the whole sizeof(i++) is replaced by the constant value 4. so, there is no assembly code for i++ at all, which is to be evaluated at the run-time.
Case 2: Run- time behavior
As, I told before Sizeof() operator is the only operator in C, which is evaluated at the compile time.But, there is an exception for this in C99 standards, for variable length arrays.
To start with, Let us consider an code snippet shown below,


Fig 4: Code containing variable length array


Let us see the output, when the above code is compiled & run ( shown in fig 5 below)


Fig 5: Output of the sizeof_run.c


From the above output it is very clear that sizeof() operator is evaluated at the run-time, One can observe the equivalent assembly code generated by the compiler as shown in the Fig 6 given below.
Also, see the difference between the assembly code in the Fig 3 & Fig 6.

Fig 6: Assembly code generated by the compiler, for variable length array.


According to the C99 standards, the sizeof() operator yields the size (in integer bytes) of its operand, which may be an expression or the parenthesized name of a type. If the type of the operand is a variable length array type, the operand is evaluated at run time; otherwise, the operand is not evaluated and the result is an integer constant, during the compile time itself.


In the next blog we will see,
1. Need of sizeof().
2. Cases where sizeof() will not work.
3. How sizeof() is different from function call.