<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Safer Code - Secure Coding In C \ C++ And More..</title>
	
	<link>http://www.safercode.com/blog</link>
	<description>Making Your Code Faster, Stronger, Safer…</description>
	<lastBuildDate>Sun, 23 Aug 2009 20:10:14 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<image><link>http://www.safercode.com/blog/logo.png</link><url>http://www.safercode.com/blog/logo.png</url><title>Safer Code</title></image><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/SaferCode" type="application/rss+xml" /><feedburner:emailServiceId>SaferCode</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item>
		<title>Large Arrays In C</title>
		<link>http://feedproxy.google.com/~r/SaferCode/~3/pJImnPjgCJw/large-arrays-in-c.html</link>
		<comments>http://www.safercode.com/blog/2009/08/24/large-arrays-in-c.html#comments</comments>
		<pubDate>Sun, 23 Aug 2009 20:09:19 +0000</pubDate>
		<dc:creator>Shantanu Goel</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Optimization]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[BSS]]></category>
		<category><![CDATA[C CPP]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[Large Arrays]]></category>
		<category><![CDATA[Programming Pearls]]></category>
		<category><![CDATA[Stack Overflo]]></category>

		<guid isPermaLink="false">http://www.safercode.com/blog/2009/08/24/large-arrays-in-c.html</guid>
		<description><![CDATA[<!-- Powered by Shantz WP Prefix Suffix. Tech Blog: http://tech.shantanugoel.com/ Secure Programming Blog: http://www.safercode.com/blog/ Blog: http://blog.shantanugoel.com/ -->Most C programmers, even beginners, would claim that arrays are easy, except those abundant off-by-one errors and they are right. Arrays are easy indeed. However, here are a few points to consider when writing a program that needs a rather large array (By the way, the thought for this article came into mind while helping [...]]]></description>
			<content:encoded><![CDATA[<!-- Powered by Shantz WP Prefix Suffix. Tech Blog: http://tech.shantanugoel.com/ Secure Programming Blog: http://www.safercode.com/blog/ Blog: http://blog.shantanugoel.com/ --><p style='border:thin dotted black; padding:3mm;background-color: rgb(250,150,250);'><strong><a href="http://feedproxy.google.com/SaferCode" rel="alternate" type="application/rss+xml">Subscribe To Our Feed</a> | <a href="http://twitter.com/safercode" rel="nofollow">Follow Us On Twitter</a> | <a href="http://feedburner.google.com/fb/a/mailverify?uri=safercode" rel="nofollow" target="_blank">Get Updates on Email</a></strong></p>
<p>Most C programmers, even beginners, would claim that arrays are easy, except those abundant off-by-one errors and they are right. Arrays are easy indeed. However, here are a few points to consider when writing a program that needs a rather large array (By the way, the thought for this article came into mind while helping a colleague to resolve an error a couple of days ago). When creating a large array (e.g. something like int a[1000][1000], which BTW takes up around 3.8 MB on most machines), you might not have any issue at all or might see either a compile time error or worse, runtime errors.<br />Why do these errors happen? Depending on your machine&#8217;s limitations you are most probably consuming the total available stack (if you used a local variable) or data memory. Depending on your compiler, these might be flagged at compile time or surface when you try to run your program. Or it might be that your compiler isn&#8217;t able to work with large arrays. What you can do to alleviate these:
<ul>
<li>The first and best way is to minimize your array size (This makes for an amazing example here from the bookd &#8220;Programming Peals&#8221;: http://www.cs.bell-labs.com/cm/cs/pearls/cto.html ) </li>
<li>Use &#8220;huge&#8221; memory model.</li>
<li>Use a global variable (or a static variable if you are particular about its visibility to the rest of the program). The stack is generally quite limited as compared to the data memory available to a program. So, a variable with static storage would ensure that you use memory from the data segment.</li>
<li>Don&#8217;t declare it as an array at all and instead use a pointer and dynamically allocate the memory required for it. You might have to use special allocation calls instead of normal malloc/calloc to get this working though (e.g. using farmalloc)</li>
<li>Create a section in assembly with the &#8220;Area&#8221; directive (or whatever it is for your particular assembler) and reserve space for your array there and refer to that array as an extern variable.</li>
</ul>
<p>The first approach is something that you should always look for. But if you can&#8217;t mimize your need any further, choose one out of the rest two. But few things to be kept in mind here that these options can still fail, e.g., when you don&#8217;t have enough RAM/heap memory remaining at runtime (of course, you would have planned for a graceful exit though in such case instead of the random crash that would have occured otherwise). But still these could be useful to you in case you don&#8217;t have any real RAM limitations but just that your compiler isn&#8217;t able to work with large objects.
<p style='border:thin dotted black; padding:3mm;background-color: rgb(250,150,250);'>© <a href="http://www.safercode.com/blog/">Safer Code</a> | <a href="http://www.safercode.com/blog/2009/08/24/large-arrays-in-c.html">Large Arrays In C</a></p>



Share and Enjoy:


	<a rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F08%2F24%2Flarge-arrays-in-c.html&amp;title=Large%20Arrays%20In%20C&amp;bodytext=Most%20C%20programmers%2C%20even%20beginners%2C%20would%20claim%20that%20arrays%20are%20easy%2C%20except%20those%20abundant%20off-by-one%20errors%20and%20they%20are%20right.%20Arrays%20are%20easy%20indeed.%20However%2C%20here%20are%20a%20few%20points%20to%20consider%20when%20writing%20a%20program%20that%20needs%20a%20rather%20large%20arra" title="Digg"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F08%2F24%2Flarge-arrays-in-c.html&amp;title=Large%20Arrays%20In%20C&amp;notes=Most%20C%20programmers%2C%20even%20beginners%2C%20would%20claim%20that%20arrays%20are%20easy%2C%20except%20those%20abundant%20off-by-one%20errors%20and%20they%20are%20right.%20Arrays%20are%20easy%20indeed.%20However%2C%20here%20are%20a%20few%20points%20to%20consider%20when%20writing%20a%20program%20that%20needs%20a%20rather%20large%20arra" title="del.icio.us"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F08%2F24%2Flarge-arrays-in-c.html&amp;t=Large%20Arrays%20In%20C" title="Facebook"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F08%2F24%2Flarge-arrays-in-c.html&amp;title=Large%20Arrays%20In%20C" title="StumbleUpon"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F08%2F24%2Flarge-arrays-in-c.html&amp;title=Large%20Arrays%20In%20C" title="Reddit"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.printfriendly.com/print?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F08%2F24%2Flarge-arrays-in-c.html&amp;partner=sociable" title="Print this article!"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/printfriendly.png" title="Print this article!" alt="Print this article!" class="sociable-hovers" /></a>


<br/><br/>
	Tags: <a href="http://www.safercode.com/blog/tag/bss" title="BSS" rel="tag nofollow">BSS</a>, <a href="http://www.safercode.com/blog/tag/c-cpp" title="C CPP" rel="tag nofollow">C CPP</a>, <a href="http://www.safercode.com/blog/tag/heap" title="heap" rel="tag nofollow">heap</a>, <a href="http://www.safercode.com/blog/tag/large-arrays" title="Large Arrays" rel="tag nofollow">Large Arrays</a>, <a href="http://www.safercode.com/blog/tag/programming-pearls" title="Programming Pearls" rel="tag nofollow">Programming Pearls</a>, <a href="http://www.safercode.com/blog/tag/stack-overflo" title="Stack Overflo" rel="tag nofollow">Stack Overflo</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.safercode.com/blog/2008/10/14/int-main-vs-void-main.html" title="int main() vs void main() (October 14, 2008)">int main() vs void main()</a> (21)</li>
</ul>

<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/SaferCode?a=pJImnPjgCJw:liK-CTJioqA:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SaferCode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=pJImnPjgCJw:liK-CTJioqA:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=pJImnPjgCJw:liK-CTJioqA:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=pJImnPjgCJw:liK-CTJioqA:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=pJImnPjgCJw:liK-CTJioqA:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=pJImnPjgCJw:liK-CTJioqA:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=pJImnPjgCJw:liK-CTJioqA:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=pJImnPjgCJw:liK-CTJioqA:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=pJImnPjgCJw:liK-CTJioqA:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SaferCode/~4/pJImnPjgCJw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.safercode.com/blog/2009/08/24/large-arrays-in-c.html/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://www.safercode.com/blog/2009/08/24/large-arrays-in-c.html</feedburner:origLink></item>
		<item>
		<title>“De-Bugging” Code before Check-in</title>
		<link>http://feedproxy.google.com/~r/SaferCode/~3/Xao3BhUoUv0/de-bugging-code-before-check-in.html</link>
		<comments>http://www.safercode.com/blog/2009/06/10/de-bugging-code-before-check-in.html#comments</comments>
		<pubDate>Tue, 09 Jun 2009 19:30:58 +0000</pubDate>
		<dc:creator>Amit Goel</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[bugs]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[crash]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[Efficiency]]></category>
		<category><![CDATA[Languages]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[safety and security]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://www.safercode.com/blog/?p=41</guid>
		<description><![CDATA[<!-- Powered by Shantz WP Prefix Suffix. Tech Blog: http://tech.shantanugoel.com/ Secure Programming Blog: http://www.safercode.com/blog/ Blog: http://blog.shantanugoel.com/ -->Even an expert programmer cannot claim of writing bug free code. Bugs are here to stay during a software development life cycle. But what every programmer needs to do is to test his code before the code goes into the main repository. So, programmers have different techniques to do this. Running Test cases, getting code [...]]]></description>
			<content:encoded><![CDATA[<!-- Powered by Shantz WP Prefix Suffix. Tech Blog: http://tech.shantanugoel.com/ Secure Programming Blog: http://www.safercode.com/blog/ Blog: http://blog.shantanugoel.com/ --><p style='border:thin dotted black; padding:3mm;background-color: rgb(250,150,250);'><strong><a href="http://feedproxy.google.com/SaferCode" rel="alternate" type="application/rss+xml">Subscribe To Our Feed</a> | <a href="http://twitter.com/safercode" rel="nofollow">Follow Us On Twitter</a> | <a href="http://feedburner.google.com/fb/a/mailverify?uri=safercode" rel="nofollow" target="_blank">Get Updates on Email</a></strong></p>
<p>Even an expert programmer cannot claim of writing bug free code. Bugs are here to stay during a software development life cycle. But what every programmer needs to do is to test his code before the code goes into the main repository. So, programmers have different techniques to do this. Running Test cases, getting code reviewed, code walk through, running manual tests, ad-hoc tests are various things performed by people and Bang!!! code goes into the repository. Let&#8217;s consider the following psuedo-code:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">char</span><span style="color: #339933;">*</span> someString <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span><span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span> malloc<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">100</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>someString <span style="color: #339933;">!=</span> NULL<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// do something</span>
<span style="color: #009900;">&#125;</span><span style="color: #b1b100;">else</span><span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// handle error condition</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><span id="more-41"></span><br />
Now, If you try to test the above code using the above mentioned testing techniques, you can never be sure that you have covered 100% code in developer testing. The code definitely seems to be fine handling the error condition if the memory allocation fails. But have you actually tested the error condition handling? Generally, all the automated test cases or running the code will make the memory allocation successful and the error condition will never get executed. Even the code reviewers will pass the code without any objection as the code is handling memory allocation failure. But you haven&#8217;t made sure that error handling is safe or not. The Bug might be in error handling scenario. </p>
<p>So, One of the best way to &#8220;de-Bug&#8221; or test your code is always to step through your code. Think that you were stepping through your code using a debugger. Now, put a breakpoint at malloc and set someString to NULL right after memory allocation is done. This will enable your error condition code to be executed and you can claim 100% coverage of testing your code before checking it in the repository. </p>
<p>The next word of advise is that not only error conditions, one should check all the possible execution paths in the code. Consider the following example:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> someInt <span style="color: #339933;">=</span> <span style="color: #0000dd;">30</span><span style="color: #339933;">;</span>
<span style="color: #993333;">char</span> someChar <span style="color: #339933;">=</span> <span style="color: #ff0000;">'c'</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> someInt<span style="color: #339933;">=</span> <span style="color: #0000dd;">32</span> <span style="color: #339933;">&amp;&amp;</span> someChar<span style="color: #339933;">==</span><span style="color: #ff0000;">'c'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// do something</span>
<span style="color: #009900;">&#125;</span><span style="color: #b1b100;">else</span><span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// handle error condition</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>If you notice, I have made a mistake in the code by typing &#8216;=&#8217; in place of &#8216;==&#8217; in the first part of &#8216;if&#8217; statement. So, even if you run test cases or use debugger, the code will easily execute &#8216;if&#8217; statement in one shot and will evaulate to true as first and second condition will always evaluate to &#8216;TRUE&#8217;. and hence, leaving a hole in the code. The error condition will never occur in this case. This can only be caught if while using a debugger, put a breakpoint inside &#8216;if&#8217; statement, and then verify both the conditions on either side of &#8216;&#038;&#038;&#8217; operator. This will lead you to find the anomaly in the code and hence, you&#8217;ll be able to kill a potential showstopper bug instantly. </p>
<p>In a nutshell, I wish to emphasize on a point is that debuggers are not meant only to be used when the defects are raised in defect trackign systems, they should be used during developmental testing of the code. I agree that this consumes a hell lot of extra time in development but isn&#8217;t it beneficial to be safe in the beginning rather than wasting time on these small issues after the software is released and have already translated into bigger crash bugs.</p>
<p style='border:thin dotted black; padding:3mm;background-color: rgb(250,150,250);'>© <a href="http://www.safercode.com/blog/">Safer Code</a> | <a href="http://www.safercode.com/blog/2009/06/10/de-bugging-code-before-check-in.html">&#8220;De-Bugging&#8221; Code before Check-in</a></p>



Share and Enjoy:


	<a rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F06%2F10%2Fde-bugging-code-before-check-in.html&amp;title=%22De-Bugging%22%20Code%20before%20Check-in&amp;bodytext=Even%20an%20expert%20programmer%20cannot%20claim%20of%20writing%20bug%20free%20code.%20Bugs%20are%20here%20to%20stay%20during%20a%20software%20development%20life%20cycle.%20But%20what%20every%20programmer%20needs%20to%20do%20is%20to%20test%20his%20code%20before%20the%20code%20goes%20into%20the%20main%20repository.%20So%2C%20programmers%20" title="Digg"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F06%2F10%2Fde-bugging-code-before-check-in.html&amp;title=%22De-Bugging%22%20Code%20before%20Check-in&amp;notes=Even%20an%20expert%20programmer%20cannot%20claim%20of%20writing%20bug%20free%20code.%20Bugs%20are%20here%20to%20stay%20during%20a%20software%20development%20life%20cycle.%20But%20what%20every%20programmer%20needs%20to%20do%20is%20to%20test%20his%20code%20before%20the%20code%20goes%20into%20the%20main%20repository.%20So%2C%20programmers%20" title="del.icio.us"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F06%2F10%2Fde-bugging-code-before-check-in.html&amp;t=%22De-Bugging%22%20Code%20before%20Check-in" title="Facebook"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F06%2F10%2Fde-bugging-code-before-check-in.html&amp;title=%22De-Bugging%22%20Code%20before%20Check-in" title="StumbleUpon"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F06%2F10%2Fde-bugging-code-before-check-in.html&amp;title=%22De-Bugging%22%20Code%20before%20Check-in" title="Reddit"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.printfriendly.com/print?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F06%2F10%2Fde-bugging-code-before-check-in.html&amp;partner=sociable" title="Print this article!"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/printfriendly.png" title="Print this article!" alt="Print this article!" class="sociable-hovers" /></a>


<br/><br/>
	Tags: <a href="http://www.safercode.com/blog/tag/bugs" title="bugs" rel="tag nofollow">bugs</a>, <a href="http://www.safercode.com/blog/tag/c" title="C" rel="tag nofollow">C</a>, <a href="http://www.safercode.com/blog/tag/crash" title="crash" rel="tag nofollow">crash</a>, <a href="http://www.safercode.com/blog/tag/debugging" title="debugging" rel="tag nofollow">debugging</a>, <a href="http://www.safercode.com/blog/tag/efficiency" title="Efficiency" rel="tag nofollow">Efficiency</a>, <a href="http://www.safercode.com/blog/tag/languages" title="Languages" rel="tag nofollow">Languages</a>, <a href="http://www.safercode.com/blog/tag/programming" title="programming" rel="tag nofollow">programming</a>, <a href="http://www.safercode.com/blog/tag/safety-and-security" title="safety and security" rel="tag nofollow">safety and security</a>, <a href="http://www.safercode.com/blog/tag/security" title="Security" rel="tag nofollow">Security</a>, <a href="http://www.safercode.com/blog/tag/testing" title="testing" rel="tag nofollow">testing</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.safercode.com/blog/2008/10/14/and-so-it-begins.html" title="And So It Begins&#8230; (October 14, 2008)">And So It Begins&#8230;</a> (0)</li>
	<li><a href="http://www.safercode.com/blog/2009/01/13/improper-variable-initialization.html" title="Improper Variable Initialization (January 13, 2009)">Improper Variable Initialization</a> (0)</li>
	<li><a href="http://www.safercode.com/blog/2009/02/10/predicting-the-rand-and-using-cryptographic-random-numbers.html" title="Predicting the rand() and using Cryptographic Random Numbers (February 10, 2009)">Predicting the rand() and using Cryptographic Random Numbers</a> (7)</li>
	<li><a href="http://www.safercode.com/blog/2008/10/14/int-main-vs-void-main.html" title="int main() vs void main() (October 14, 2008)">int main() vs void main()</a> (21)</li>
	<li><a href="http://www.safercode.com/blog/2008/11/18/all-input-is-evil.html" title="All Input is Evil (November 18, 2008)">All Input is Evil</a> (3)</li>
</ul>

<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/SaferCode?a=Xao3BhUoUv0:T5i-za-2WGs:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SaferCode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=Xao3BhUoUv0:T5i-za-2WGs:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=Xao3BhUoUv0:T5i-za-2WGs:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=Xao3BhUoUv0:T5i-za-2WGs:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=Xao3BhUoUv0:T5i-za-2WGs:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=Xao3BhUoUv0:T5i-za-2WGs:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=Xao3BhUoUv0:T5i-za-2WGs:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=Xao3BhUoUv0:T5i-za-2WGs:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=Xao3BhUoUv0:T5i-za-2WGs:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SaferCode/~4/Xao3BhUoUv0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.safercode.com/blog/2009/06/10/de-bugging-code-before-check-in.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.safercode.com/blog/2009/06/10/de-bugging-code-before-check-in.html</feedburner:origLink></item>
		<item>
		<title>A Bug Is Not Always Where It Seems To Be</title>
		<link>http://feedproxy.google.com/~r/SaferCode/~3/eo6LKz9rD7I/a-bug-is-not-always-where-it-seems-to-be.html</link>
		<comments>http://www.safercode.com/blog/2009/05/12/a-bug-is-not-always-where-it-seems-to-be.html#comments</comments>
		<pubDate>Tue, 12 May 2009 13:30:00 +0000</pubDate>
		<dc:creator>Shantanu Goel</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[500 mile email]]></category>
		<category><![CDATA[bugs]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[OOo]]></category>
		<category><![CDATA[Open Office Bug]]></category>
		<category><![CDATA[Open Office tuesday print bug]]></category>
		<category><![CDATA[OpenOffice.org]]></category>

		<guid isPermaLink="false">http://www.safercode.com/blog/2009/05/13/a-bug-is-not-always-where-it-seems-to-be.html</guid>
		<description><![CDATA[<!-- Powered by Shantz WP Prefix Suffix. Tech Blog: http://tech.shantanugoel.com/ Secure Programming Blog: http://www.safercode.com/blog/ Blog: http://blog.shantanugoel.com/ -->Many people would agree with me when I say that the hardest part of fixing a bug is to find where it is originating from. It has happened to me quite a number of times that a certain module exhibits a particularly wild behaviour making me go mad on its developer but as I dug [...]]]></description>
			<content:encoded><![CDATA[<!-- Powered by Shantz WP Prefix Suffix. Tech Blog: http://tech.shantanugoel.com/ Secure Programming Blog: http://www.safercode.com/blog/ Blog: http://blog.shantanugoel.com/ --><p style='border:thin dotted black; padding:3mm;background-color: rgb(250,150,250);'><strong><a href="http://feedproxy.google.com/SaferCode" rel="alternate" type="application/rss+xml">Subscribe To Our Feed</a> | <a href="http://twitter.com/safercode" rel="nofollow">Follow Us On Twitter</a> | <a href="http://feedburner.google.com/fb/a/mailverify?uri=safercode" rel="nofollow" target="_blank">Get Updates on Email</a></strong></p>
<p>Many people would agree with me when I say that the hardest part of fixing a bug is to find where it is originating from. It has happened to me quite a number of times that a certain module exhibits a particularly wild behaviour making me go mad on its developer but as I dug deeper, the cuplrit turned out to be someone who had not even heard of that module. <img src='http://www.safercode.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Today I bring to you such an example of a nice bug, which I’ll term as (like many others):</p>
</p>
<h3 align="center">OpenOffice.org Cannot Print On Tuesdays Bug</h3>
</p>
<p>OpenOffice.org (also known as OOo or just Open Office) is a free and widely used MS Office alternative and a lot of its users reported in recently that it would just stop printing on every tuesday. Come Wednesday, everything would be just fine and dandy, but for just less than a week till Tuesday showed its face again. Now, before I continue to unravel the mystery behind this unique bug, let me outrightly clear it out to my Indian friends that OOo is not devotee of Lord Hanuman, deciding to go on a fast on Tuedays to offer its obesceinces. <img src='http://www.safercode.com/blog/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p>Well, after days of discussions, and people blaming everything from OOo to cups (the printer daemon), printer drivers, or the printer itself, one enterprising soul decided to investigate and found out that if he changed the “CreationDate” tag in the generated postscript file to replace the “Tue” of Tuesday with something else, the file happily printed. </p>
<p> <span id="more-39"></span>
<p>His doubt about this being a cups issue strengthened when he noticed that this only occurs with OOo because other tools like evince omit this particular tag and hence escape cups’ wrath. On looking further he found out that somehow the Tuesday file is not being identified as a valid postscript file by cups but as something else. But the culprit is not cups, the cups script was actually using another utility “file” to do this identification and whenever T occurs at the file’s fourth byte, it is being identified as an “Erlang Jam” file isntead of a postscript file. This bug is listed <a href="https://bugs.launchpad.net/ubuntu/+source/file/+bug/248619" target="_blank" rel="nofollow">here</a>. Now, he couldn’t solve the issue with the file utility, but the correct identification of the bug’s origin allowed him to make a quick workaround to solve his issue. He just made a small modification to the cups script and changed:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">cat</span> <span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #007800;">$INPUT_TEMP</span></pre></div></div>

<p>to</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">cat</span> <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">sed</span> <span style="color: #660033;">-e</span> <span style="color: #ff0000;">'s/^%%CreationDate: (Tue/%%CreationDate: (tue/'</span> <span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #007800;">$INPUT_TEMP</span></pre></div></div>

<p>This change changed the “Tue” to “tue” whenever it was found int he creation date hence circumventing the issue.</p>
<p>Let this be an example for you to remember always “A bug is not always where it seems to be” and that even the weirdest bugs are possible. If you are still in doubt, read this: <a href="http://www.ibiblio.org/harris/500milemail.html" target="_blank" rel="nofollow">The Case of the 500 Mile E-Mail</a></p>
<p style='border:thin dotted black; padding:3mm;background-color: rgb(250,150,250);'>© <a href="http://www.safercode.com/blog/">Safer Code</a> | <a href="http://www.safercode.com/blog/2009/05/12/a-bug-is-not-always-where-it-seems-to-be.html">A Bug Is Not Always Where It Seems To Be</a></p>



Share and Enjoy:


	<a rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F05%2F12%2Fa-bug-is-not-always-where-it-seems-to-be.html&amp;title=A%20Bug%20Is%20Not%20Always%20Where%20It%20Seems%20To%20Be&amp;bodytext=Many%20people%20would%20agree%20with%20me%20when%20I%20say%20that%20the%20hardest%20part%20of%20fixing%20a%20bug%20is%20to%20find%20where%20it%20is%20originating%20from.%20It%20has%20happened%20to%20me%20quite%20a%20number%20of%20times%20that%20a%20certain%20module%20exhibits%20a%20particularly%20wild%20behaviour%20making%20me%20go%20mad%20on%20i" title="Digg"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F05%2F12%2Fa-bug-is-not-always-where-it-seems-to-be.html&amp;title=A%20Bug%20Is%20Not%20Always%20Where%20It%20Seems%20To%20Be&amp;notes=Many%20people%20would%20agree%20with%20me%20when%20I%20say%20that%20the%20hardest%20part%20of%20fixing%20a%20bug%20is%20to%20find%20where%20it%20is%20originating%20from.%20It%20has%20happened%20to%20me%20quite%20a%20number%20of%20times%20that%20a%20certain%20module%20exhibits%20a%20particularly%20wild%20behaviour%20making%20me%20go%20mad%20on%20i" title="del.icio.us"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F05%2F12%2Fa-bug-is-not-always-where-it-seems-to-be.html&amp;t=A%20Bug%20Is%20Not%20Always%20Where%20It%20Seems%20To%20Be" title="Facebook"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F05%2F12%2Fa-bug-is-not-always-where-it-seems-to-be.html&amp;title=A%20Bug%20Is%20Not%20Always%20Where%20It%20Seems%20To%20Be" title="StumbleUpon"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F05%2F12%2Fa-bug-is-not-always-where-it-seems-to-be.html&amp;title=A%20Bug%20Is%20Not%20Always%20Where%20It%20Seems%20To%20Be" title="Reddit"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.printfriendly.com/print?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F05%2F12%2Fa-bug-is-not-always-where-it-seems-to-be.html&amp;partner=sociable" title="Print this article!"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/printfriendly.png" title="Print this article!" alt="Print this article!" class="sociable-hovers" /></a>


<br/><br/>
	Tags: <a href="http://www.safercode.com/blog/tag/500-mile-email" title="500 mile email" rel="tag nofollow">500 mile email</a>, <a href="http://www.safercode.com/blog/tag/bugs" title="bugs" rel="tag nofollow">bugs</a>, <a href="http://www.safercode.com/blog/tag/debugging" title="debugging" rel="tag nofollow">debugging</a>, <a href="http://www.safercode.com/blog/tag/ooo" title="OOo" rel="tag nofollow">OOo</a>, <a href="http://www.safercode.com/blog/tag/open-office-bug" title="Open Office Bug" rel="tag nofollow">Open Office Bug</a>, <a href="http://www.safercode.com/blog/tag/open-office-tuesday-print-bug" title="Open Office tuesday print bug" rel="tag nofollow">Open Office tuesday print bug</a>, <a href="http://www.safercode.com/blog/tag/openofficeorg" title="OpenOffice.org" rel="tag nofollow">OpenOffice.org</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.safercode.com/blog/2009/06/10/de-bugging-code-before-check-in.html" title="&#8220;De-Bugging&#8221; Code before Check-in (June 10, 2009)">&#8220;De-Bugging&#8221; Code before Check-in</a> (0)</li>
</ul>

<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/SaferCode?a=eo6LKz9rD7I:L0tT7JxAQEc:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SaferCode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=eo6LKz9rD7I:L0tT7JxAQEc:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=eo6LKz9rD7I:L0tT7JxAQEc:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=eo6LKz9rD7I:L0tT7JxAQEc:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=eo6LKz9rD7I:L0tT7JxAQEc:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=eo6LKz9rD7I:L0tT7JxAQEc:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=eo6LKz9rD7I:L0tT7JxAQEc:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=eo6LKz9rD7I:L0tT7JxAQEc:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=eo6LKz9rD7I:L0tT7JxAQEc:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SaferCode/~4/eo6LKz9rD7I" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.safercode.com/blog/2009/05/12/a-bug-is-not-always-where-it-seems-to-be.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.safercode.com/blog/2009/05/12/a-bug-is-not-always-where-it-seems-to-be.html</feedburner:origLink></item>
		<item>
		<title>Find The Offset Of An Element In A Structure In C- offsetof()</title>
		<link>http://feedproxy.google.com/~r/SaferCode/~3/PIDlnndlBDo/find-element-offset-structure-c-offsetof.html</link>
		<comments>http://www.safercode.com/blog/2009/05/05/find-element-offset-structure-c-offsetof.html#comments</comments>
		<pubDate>Tue, 05 May 2009 13:30:00 +0000</pubDate>
		<dc:creator>Shantanu Goel</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[element offset]]></category>
		<category><![CDATA[element offset in structure]]></category>
		<category><![CDATA[offsetof]]></category>
		<category><![CDATA[Portability]]></category>
		<category><![CDATA[structure in c]]></category>
		<category><![CDATA[structure offset]]></category>

		<guid isPermaLink="false">http://www.safercode.com/blog/2009/05/05/find-element-offset-structure-c-offsetof.html</guid>
		<description><![CDATA[<!-- Powered by Shantz WP Prefix Suffix. Tech Blog: http://tech.shantanugoel.com/ Secure Programming Blog: http://www.safercode.com/blog/ Blog: http://blog.shantanugoel.com/ -->First of all, I apologize for the decreased frequency of updates. We have been quite busy with our offline lives and primary livelihoods lately keeping us away from posting much. But we intend to not let it remain like this for much longer. I’m posting a short article today about something that almost everyone of [...]]]></description>
			<content:encoded><![CDATA[<!-- Powered by Shantz WP Prefix Suffix. Tech Blog: http://tech.shantanugoel.com/ Secure Programming Blog: http://www.safercode.com/blog/ Blog: http://blog.shantanugoel.com/ --><p style='border:thin dotted black; padding:3mm;background-color: rgb(250,150,250);'><strong><a href="http://feedproxy.google.com/SaferCode" rel="alternate" type="application/rss+xml">Subscribe To Our Feed</a> | <a href="http://twitter.com/safercode" rel="nofollow">Follow Us On Twitter</a> | <a href="http://feedburner.google.com/fb/a/mailverify?uri=safercode" rel="nofollow" target="_blank">Get Updates on Email</a></strong></p>
<p>First of all, I apologize for the decreased frequency of updates. We have been quite busy with our offline lives and primary livelihoods lately keeping us away from posting much. But we intend to not let it remain like this for much longer. I’m posting a short article today about something that almost everyone of us has had to do at some point of time, i.e., to find the offset (or relative position in bytes) of an element in a structure. Let’s take the following structure as an example:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">struct</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #993333;">char</span> a<span style="color: #339933;">;</span>
  <span style="color: #993333;">int</span> b<span style="color: #339933;">;</span>
  <span style="color: #993333;">char</span> c<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>example<span style="color: #339933;">;</span></pre></div></div>

<p>Now, if I were to ask you to find out the element b’s offset in the above structure, you won’t probably be able to answer with complete confidence unless I tell you the compiler you are working with and whether packing has been turned on or not. The easiest way to find it out is to use a small snippet of code to do it for us and that always works. e.g.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">struct</span> example s1<span style="color: #339933;">;</span>
<span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> offset<span style="color: #339933;">;</span>
offset <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">&amp;</span>s1.<span style="color: #202020;">b</span> <span style="color: #339933;">-</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">&amp;</span>s1<span style="color: #339933;">;</span></pre></div></div>

<p>The above snippet will work, but not always (<a title="32 bit vs 64 bit" href="http://www.safercode.com/blog/2009/03/10/portable-code-how-to-check-if-a-machine-is-32-bit-or-64-bit.html" target="_blank" rel="me">Hint</a>). Many people use a much simplified form, which does not involve any pointer arithmetic:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> offset<span style="color: #339933;">;</span>
offset <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>example <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span>b<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The above code is much simpler/faster but again, it might not be portable. So, what is the best method to do this portably. It’s quite simple really, just use the “<strong>offsetof</strong>” macro provided by any ANSI-C compliant compiler. It is present in stddef.h and can be used in the following way:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">size_t offset<span style="color: #339933;">;</span>
offset <span style="color: #339933;">=</span> offsetof<span style="color: #009900;">&#40;</span>example<span style="color: #339933;">,</span> b<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>If you noticed, offsetof() also presents another advantage to you like the 2nd method, i.e., it does not require an extra structure to be defined. In fact, this macro is defined in forms similar to our method 2 but the benefit is that it ensures portability for your code.</p>
<p style='border:thin dotted black; padding:3mm;background-color: rgb(250,150,250);'>© <a href="http://www.safercode.com/blog/">Safer Code</a> | <a href="http://www.safercode.com/blog/2009/05/05/find-element-offset-structure-c-offsetof.html">Find The Offset Of An Element In A Structure In C- offsetof()</a></p>



Share and Enjoy:


	<a rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F05%2F05%2Ffind-element-offset-structure-c-offsetof.html&amp;title=Find%20The%20Offset%20Of%20An%20Element%20In%20A%20Structure%20In%20C-%20offsetof%28%29&amp;bodytext=First%20of%20all%2C%20I%20apologize%20for%20the%20decreased%20frequency%20of%20updates.%20We%20have%20been%20quite%20busy%20with%20our%20offline%20lives%20and%20primary%20livelihoods%20lately%20keeping%20us%20away%20from%20posting%20much.%20But%20we%20intend%20to%20not%20let%20it%20remain%20like%20this%20for%20much%20longer.%20I%E2%80%99m%20pos" title="Digg"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F05%2F05%2Ffind-element-offset-structure-c-offsetof.html&amp;title=Find%20The%20Offset%20Of%20An%20Element%20In%20A%20Structure%20In%20C-%20offsetof%28%29&amp;notes=First%20of%20all%2C%20I%20apologize%20for%20the%20decreased%20frequency%20of%20updates.%20We%20have%20been%20quite%20busy%20with%20our%20offline%20lives%20and%20primary%20livelihoods%20lately%20keeping%20us%20away%20from%20posting%20much.%20But%20we%20intend%20to%20not%20let%20it%20remain%20like%20this%20for%20much%20longer.%20I%E2%80%99m%20pos" title="del.icio.us"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F05%2F05%2Ffind-element-offset-structure-c-offsetof.html&amp;t=Find%20The%20Offset%20Of%20An%20Element%20In%20A%20Structure%20In%20C-%20offsetof%28%29" title="Facebook"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F05%2F05%2Ffind-element-offset-structure-c-offsetof.html&amp;title=Find%20The%20Offset%20Of%20An%20Element%20In%20A%20Structure%20In%20C-%20offsetof%28%29" title="StumbleUpon"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F05%2F05%2Ffind-element-offset-structure-c-offsetof.html&amp;title=Find%20The%20Offset%20Of%20An%20Element%20In%20A%20Structure%20In%20C-%20offsetof%28%29" title="Reddit"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.printfriendly.com/print?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F05%2F05%2Ffind-element-offset-structure-c-offsetof.html&amp;partner=sociable" title="Print this article!"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/printfriendly.png" title="Print this article!" alt="Print this article!" class="sociable-hovers" /></a>


<br/><br/>
	Tags: <a href="http://www.safercode.com/blog/tag/c" title="C" rel="tag nofollow">C</a>, <a href="http://www.safercode.com/blog/tag/element-offset" title="element offset" rel="tag nofollow">element offset</a>, <a href="http://www.safercode.com/blog/tag/element-offset-in-structure" title="element offset in structure" rel="tag nofollow">element offset in structure</a>, <a href="http://www.safercode.com/blog/tag/offsetof" title="offsetof" rel="tag nofollow">offsetof</a>, <a href="http://www.safercode.com/blog/tag/portability" title="Portability" rel="tag nofollow">Portability</a>, <a href="http://www.safercode.com/blog/tag/structure-in-c" title="structure in c" rel="tag nofollow">structure in c</a>, <a href="http://www.safercode.com/blog/tag/structure-offset" title="structure offset" rel="tag nofollow">structure offset</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.safercode.com/blog/2009/02/24/volatile-c-keyword-myths-dispelled.html" title="Volatile: C Keyword Myths Dispelled (February 24, 2009)">Volatile: C Keyword Myths Dispelled</a> (12)</li>
	<li><a href="http://www.safercode.com/blog/2008/11/11/validating-untrusted-string-inputs.html" title="Validating Untrusted String Inputs (November 11, 2008)">Validating Untrusted String Inputs</a> (1)</li>
	<li><a href="http://www.safercode.com/blog/2008/10/21/validating-untrusted-integer-inputs.html" title="Validating Untrusted Integer Inputs (October 21, 2008)">Validating Untrusted Integer Inputs</a> (6)</li>
	<li><a href="http://www.safercode.com/blog/2008/12/02/unsafe-functions-in-c-and-their-safer-replacements-strings-part-ii.html" title="Unsafe Functions In C And Their Safer Replacements: Strings Part II (December 2, 2008)">Unsafe Functions In C And Their Safer Replacements: Strings Part II</a> (8)</li>
	<li><a href="http://www.safercode.com/blog/2008/11/04/unsafe-functions-in-c-and-their-safer-replacements-strings-part-i.html" title="Unsafe Functions In C And Their Safer Replacements: Strings Part I (November 4, 2008)">Unsafe Functions In C And Their Safer Replacements: Strings Part I</a> (7)</li>
</ul>

<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/SaferCode?a=PIDlnndlBDo:YDR9nw53MR8:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SaferCode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=PIDlnndlBDo:YDR9nw53MR8:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=PIDlnndlBDo:YDR9nw53MR8:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=PIDlnndlBDo:YDR9nw53MR8:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=PIDlnndlBDo:YDR9nw53MR8:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=PIDlnndlBDo:YDR9nw53MR8:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=PIDlnndlBDo:YDR9nw53MR8:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=PIDlnndlBDo:YDR9nw53MR8:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=PIDlnndlBDo:YDR9nw53MR8:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SaferCode/~4/PIDlnndlBDo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.safercode.com/blog/2009/05/05/find-element-offset-structure-c-offsetof.html/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://www.safercode.com/blog/2009/05/05/find-element-offset-structure-c-offsetof.html</feedburner:origLink></item>
		<item>
		<title>Lint your code: Find probable mistakes much before testing</title>
		<link>http://feedproxy.google.com/~r/SaferCode/~3/HCLdPU_hyJg/lint-your-code-find-probable-mistakes-much-before-testing.html</link>
		<comments>http://www.safercode.com/blog/2009/03/23/lint-your-code-find-probable-mistakes-much-before-testing.html#comments</comments>
		<pubDate>Mon, 23 Mar 2009 18:15:16 +0000</pubDate>
		<dc:creator>Amit Goel</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[buffer overflow]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Flex Lint]]></category>
		<category><![CDATA[LINT]]></category>
		<category><![CDATA[MISRA]]></category>
		<category><![CDATA[PC Lint]]></category>
		<category><![CDATA[Safety]]></category>
		<category><![CDATA[warnings]]></category>

		<guid isPermaLink="false">http://www.safercode.com/blog/?p=37</guid>
		<description><![CDATA[<!-- Powered by Shantz WP Prefix Suffix. Tech Blog: http://tech.shantanugoel.com/ Secure Programming Blog: http://www.safercode.com/blog/ Blog: http://blog.shantanugoel.com/ -->Every programmer, no matter how great he is, makes mistakes sometime or the other while coding. Although every compiler tries its best to put across every possible error during compilation,many mistakes skip the wrath of compiler. Some are seemingly very innocent and very tough to be caught even during code review, sometimes even get through [...]]]></description>
			<content:encoded><![CDATA[<!-- Powered by Shantz WP Prefix Suffix. Tech Blog: http://tech.shantanugoel.com/ Secure Programming Blog: http://www.safercode.com/blog/ Blog: http://blog.shantanugoel.com/ --><p style='border:thin dotted black; padding:3mm;background-color: rgb(250,150,250);'><strong><a href="http://feedproxy.google.com/SaferCode" rel="alternate" type="application/rss+xml">Subscribe To Our Feed</a> | <a href="http://twitter.com/safercode" rel="nofollow">Follow Us On Twitter</a> | <a href="http://feedburner.google.com/fb/a/mailverify?uri=safercode" rel="nofollow" target="_blank">Get Updates on Email</a></strong></p>
<p>Every programmer, no matter how great he is, makes mistakes sometime or the other while coding. Although every compiler tries its best to put across every possible error during compilation,many mistakes skip the wrath of compiler. Some are seemingly very innocent and very tough to be caught even during code review, sometimes even get through the cycle of testing. The real face of these mistakes show up always on the customer side by crashing the system.</p>
<p>Consider the following example:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> multiply<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> m<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> n<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #993333;">int</span> result <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
	result <span style="color: #339933;">=</span> m <span style="color: #339933;">*</span> n<span style="color: #339933;">;</span>	
	<span style="color: #b1b100;">return</span> 	result<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> func<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #993333;">int</span> m <span style="color: #339933;">=</span> <span style="color: #0000dd;">32767</span><span style="color: #339933;">;</span>
	<span style="color: #993333;">int</span> n <span style="color: #339933;">=</span> <span style="color: #0000dd;">32767</span><span style="color: #339933;">;</span>
	<span style="color: #993333;">int</span> result <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
	result <span style="color: #339933;">=</span> multiply<span style="color: #009900;">&#40;</span> m<span style="color: #339933;">,</span> n <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><span id="more-37"></span><br />
In this example, if you notice, the result always overrun the maximum value of an integer (int being of 16 bits). Now, for any compiler, this code seems to be perfect. But if you lint this code, the lint tool will definitely raise a warning about this potential bug. This bug if overlooked, can cause havoc in any system in crucial scenarios. </p>
<p>Similarly, there are many more example like these which can be caught while linting the code. Quite a few significant but obvious problems like buffer overrun, array index out of bounds, uninitialized variables causing junk in junk out can be caught using any of the good lint tools. This process of linting makes the code safe, secure and strong enough to withstand any kind of malicious input injections or buffer overrun attacks. Ofcourse, the complex scenarios can get skipped by some of the tools but still, it definitely is a better steo to catch the bug early. Quite a few tools are available in the market but i&#8217;ll recommend a tools can PC-Lint(Windows)/FlexLint(Linux). This tool is pretty good as it catches almost every obvious flaw which gets skipped by the developers or code reviewers eyes. It follows the guidelines given in MISRA (Motor Industry Software Reliability Assocation)standard and strictly adhers to that.</p>
<p>These linting tools generally have their properietary algorithms but in general, they all follow the same approach of static analysis of source code. Following are examples of some of the problems which these tools are capable of finding during the lint process.</p>
<li>Accidental assignment (= compared with ==)</li>
<li>Bad pointer arithmetic</li>
<li>Accidental booleans</li>
<li>Bad use of macros</li>
<li>Use of undefined external methods (ST20 compiler assumes int func(void))</li>
<li>Uninitialised variables</li>
<li>Unsafe array usage</li>
<li>Signed/unsigned data type mix-ups</li>
<li>Bad use of casts</li>
<li>Memory leaks (over-use of CMM and API heap). Too much reliance on dynamic memory allocation.</li>
<p>Linting your code during development is very important as it can make your code much safer. It definitely does add to the build time and it might take few extra seconds to get the final object file, but isn&#8217;t it worth the hassle if you are saved from deadly bugs?
<p style='border:thin dotted black; padding:3mm;background-color: rgb(250,150,250);'>© <a href="http://www.safercode.com/blog/">Safer Code</a> | <a href="http://www.safercode.com/blog/2009/03/23/lint-your-code-find-probable-mistakes-much-before-testing.html">Lint your code: Find probable mistakes much before testing</a></p>



Share and Enjoy:


	<a rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F03%2F23%2Flint-your-code-find-probable-mistakes-much-before-testing.html&amp;title=Lint%20your%20code%3A%20Find%20probable%20mistakes%20much%20before%20testing&amp;bodytext=Every%20programmer%2C%20no%20matter%20how%20great%20he%20is%2C%20makes%20mistakes%20sometime%20or%20the%20other%20while%20coding.%20Although%20every%20compiler%20tries%20its%20best%20to%20put%20across%20every%20possible%20error%20during%20compilation%2Cmany%20mistakes%20skip%20the%20wrath%20of%20compiler.%20Some%20are%20seemingly%20" title="Digg"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F03%2F23%2Flint-your-code-find-probable-mistakes-much-before-testing.html&amp;title=Lint%20your%20code%3A%20Find%20probable%20mistakes%20much%20before%20testing&amp;notes=Every%20programmer%2C%20no%20matter%20how%20great%20he%20is%2C%20makes%20mistakes%20sometime%20or%20the%20other%20while%20coding.%20Although%20every%20compiler%20tries%20its%20best%20to%20put%20across%20every%20possible%20error%20during%20compilation%2Cmany%20mistakes%20skip%20the%20wrath%20of%20compiler.%20Some%20are%20seemingly%20" title="del.icio.us"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F03%2F23%2Flint-your-code-find-probable-mistakes-much-before-testing.html&amp;t=Lint%20your%20code%3A%20Find%20probable%20mistakes%20much%20before%20testing" title="Facebook"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F03%2F23%2Flint-your-code-find-probable-mistakes-much-before-testing.html&amp;title=Lint%20your%20code%3A%20Find%20probable%20mistakes%20much%20before%20testing" title="StumbleUpon"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F03%2F23%2Flint-your-code-find-probable-mistakes-much-before-testing.html&amp;title=Lint%20your%20code%3A%20Find%20probable%20mistakes%20much%20before%20testing" title="Reddit"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.printfriendly.com/print?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F03%2F23%2Flint-your-code-find-probable-mistakes-much-before-testing.html&amp;partner=sociable" title="Print this article!"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/printfriendly.png" title="Print this article!" alt="Print this article!" class="sociable-hovers" /></a>


<br/><br/>
	Tags: <a href="http://www.safercode.com/blog/tag/buffer-overflow" title="buffer overflow" rel="tag nofollow">buffer overflow</a>, <a href="http://www.safercode.com/blog/tag/c" title="C" rel="tag nofollow">C</a>, <a href="http://www.safercode.com/blog/tag/flex-lint" title="Flex Lint" rel="tag nofollow">Flex Lint</a>, <a href="http://www.safercode.com/blog/tag/lint" title="LINT" rel="tag nofollow">LINT</a>, <a href="http://www.safercode.com/blog/tag/misra" title="MISRA" rel="tag nofollow">MISRA</a>, <a href="http://www.safercode.com/blog/tag/pc-lint" title="PC Lint" rel="tag nofollow">PC Lint</a>, <a href="http://www.safercode.com/blog/tag/safety" title="Safety" rel="tag nofollow">Safety</a>, <a href="http://www.safercode.com/blog/tag/warnings" title="warnings" rel="tag nofollow">warnings</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.safercode.com/blog/2008/10/21/validating-untrusted-integer-inputs.html" title="Validating Untrusted Integer Inputs (October 21, 2008)">Validating Untrusted Integer Inputs</a> (6)</li>
	<li><a href="http://www.safercode.com/blog/2008/11/11/validating-untrusted-string-inputs.html" title="Validating Untrusted String Inputs (November 11, 2008)">Validating Untrusted String Inputs</a> (1)</li>
	<li><a href="http://www.safercode.com/blog/2008/12/02/unsafe-functions-in-c-and-their-safer-replacements-strings-part-ii.html" title="Unsafe Functions In C And Their Safer Replacements: Strings Part II (December 2, 2008)">Unsafe Functions In C And Their Safer Replacements: Strings Part II</a> (8)</li>
	<li><a href="http://www.safercode.com/blog/2008/11/04/unsafe-functions-in-c-and-their-safer-replacements-strings-part-i.html" title="Unsafe Functions In C And Their Safer Replacements: Strings Part I (November 4, 2008)">Unsafe Functions In C And Their Safer Replacements: Strings Part I</a> (7)</li>
	<li><a href="http://www.safercode.com/blog/2008/10/14/int-main-vs-void-main.html" title="int main() vs void main() (October 14, 2008)">int main() vs void main()</a> (21)</li>
</ul>

<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/SaferCode?a=HCLdPU_hyJg:vnY-Xfil1D8:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SaferCode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=HCLdPU_hyJg:vnY-Xfil1D8:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=HCLdPU_hyJg:vnY-Xfil1D8:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=HCLdPU_hyJg:vnY-Xfil1D8:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=HCLdPU_hyJg:vnY-Xfil1D8:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=HCLdPU_hyJg:vnY-Xfil1D8:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=HCLdPU_hyJg:vnY-Xfil1D8:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=HCLdPU_hyJg:vnY-Xfil1D8:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=HCLdPU_hyJg:vnY-Xfil1D8:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SaferCode/~4/HCLdPU_hyJg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.safercode.com/blog/2009/03/23/lint-your-code-find-probable-mistakes-much-before-testing.html/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://www.safercode.com/blog/2009/03/23/lint-your-code-find-probable-mistakes-much-before-testing.html</feedburner:origLink></item>
		<item>
		<title>Portable Code: How To Check If A Machine Is 32 Bit Or 64 Bit</title>
		<link>http://feedproxy.google.com/~r/SaferCode/~3/ralg1dUJXVM/portable-code-how-to-check-if-a-machine-is-32-bit-or-64-bit.html</link>
		<comments>http://www.safercode.com/blog/2009/03/10/portable-code-how-to-check-if-a-machine-is-32-bit-or-64-bit.html#comments</comments>
		<pubDate>Tue, 10 Mar 2009 13:30:00 +0000</pubDate>
		<dc:creator>Shantanu Goel</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Portability]]></category>
		<category><![CDATA[32–bit]]></category>
		<category><![CDATA[64–bit]]></category>
		<category><![CDATA[Architectue]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[check machine 64 bit]]></category>
		<category><![CDATA[CPP]]></category>
		<category><![CDATA[Data Model]]></category>
		<category><![CDATA[data models]]></category>
		<category><![CDATA[data sizes]]></category>
		<category><![CDATA[data types]]></category>
		<category><![CDATA[function pointers]]></category>
		<category><![CDATA[Hardware Architecture]]></category>
		<category><![CDATA[ILP32]]></category>
		<category><![CDATA[ILP64]]></category>
		<category><![CDATA[LLP64]]></category>
		<category><![CDATA[LP32]]></category>
		<category><![CDATA[LP64]]></category>
		<category><![CDATA[pointers]]></category>
		<category><![CDATA[Portable code]]></category>
		<category><![CDATA[Programming Model]]></category>
		<category><![CDATA[SILP64]]></category>
		<category><![CDATA[writing portable code]]></category>

		<guid isPermaLink="false">http://www.safercode.com/blog/2009/03/10/portable-code-how-to-check-if-a-machine-is-32-bit-or-64-bit.html</guid>
		<description><![CDATA[<!-- Powered by Shantz WP Prefix Suffix. Tech Blog: http://tech.shantanugoel.com/ Secure Programming Blog: http://www.safercode.com/blog/ Blog: http://blog.shantanugoel.com/ -->Writing portable code is very important but it is&#160;one of the aspects that most people neglect until it is too late to realize its importance. Till few years ago, most people writing code for personal computers were not worried about the data sizes on their machines. They didn&#8217;t even think whether the machines, on which [...]]]></description>
			<content:encoded><![CDATA[<!-- Powered by Shantz WP Prefix Suffix. Tech Blog: http://tech.shantanugoel.com/ Secure Programming Blog: http://www.safercode.com/blog/ Blog: http://blog.shantanugoel.com/ --><p style='border:thin dotted black; padding:3mm;background-color: rgb(250,150,250);'><strong><a href="http://feedproxy.google.com/SaferCode" rel="alternate" type="application/rss+xml">Subscribe To Our Feed</a> | <a href="http://twitter.com/safercode" rel="nofollow">Follow Us On Twitter</a> | <a href="http://feedburner.google.com/fb/a/mailverify?uri=safercode" rel="nofollow" target="_blank">Get Updates on Email</a></strong></p>
<p>Writing portable code is very important but it is&nbsp;one of the aspects that most people neglect until it is too late to realize its importance. Till few years ago, most people writing code for personal computers were not worried about the data sizes on their machines. They didn&rsquo;t even think whether the machines, on which their code would be running, would be 32 bit or 64 bit. But the recent advent of 64 bit machines in normal every-day usage has them running helter-skelter to get their programs into shape. Many of these programs would like to run the same code base on 32 bit as well as 64 bit machines. There are many ways to do it. A few allow us to use data types that would work as expected in both machines while in other ways, they explicitly check for the architecture of the machine and carry out their tasks accordingly. Before I give you the code to run this check, let&rsquo;s see a bit of theory behind it.</p>
<p>First, let&rsquo;s be clear that the discussion we will be doing now will not always give you the &ldquo;<strong>hardware architecture</strong>&rdquo; of a machine. Rather it&rsquo;ll allow you to know the &ldquo;<strong>Programming Model</strong>&rdquo; (or <strong>Data Model</strong>)that the OS or your compiler enforces on you. What I mean is that if you run a 32 bit OS on top of your latest 64 bit processor based system, it will still mean a 32 bit&nbsp;programming model for you. Infact, if you were to compile your programs using the ancient Turbo C compiler, you&rsquo;d be in for an even bigger surprise <img src='http://www.safercode.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .&nbsp;That said,&nbsp;ultimately the programming model&nbsp;is what you&rsquo;d be interested in knowing to make sure that your program can compile and run accurately on that particular system. The most common programming models in use are as below:</p>
<table border="1">
<tbody>
<tr>
<td>Datatype</td>
<td>LP64</td>
<td>ILP64</td>
<td>SILP64</td>
<td>LLP64</td>
<td>ILP32</td>
<td>LP32</td>
</tr>
<tr>
<td>char</td>
<td>8</td>
<td>8</td>
<td>8</td>
<td>8</td>
<td>8</td>
<td>8</td>
</tr>
<tr>
<td>short</td>
<td>16</td>
<td>16</td>
<td>64</td>
<td>16</td>
<td>16</td>
<td>16</td>
</tr>
<tr>
<td>int</td>
<td>32</td>
<td>64</td>
<td>64</td>
<td>32</td>
<td>32</td>
<td>16</td>
</tr>
<tr>
<td>long</td>
<td>64</td>
<td>64</td>
<td>64</td>
<td>32</td>
<td>32</td>
<td>32</td>
</tr>
<tr>
<td>long long</td>
<td>64</td>
<td>64</td>
<td>64</td>
<td>64</td>
<td>64</td>
<td>64</td>
</tr>
<tr>
<td>pointer</td>
<td>64</td>
<td>64</td>
<td>64</td>
<td>64</td>
<td>32</td>
<td>32</td>
</tr>
</tbody>
</table>
<p>
<span id="more-35"></span><br />
So, what do we infer from this table? The glaring issues are that we can no longer depend on the sizes of data types with which we work. If your program does not make use of the data type sizes (either explicitly or implicity, e.g. by type conversion like converting between pointers and integers), most probably you will be safe by just recompiling your code for the new machine without changing it. Otherwise, a safe bet is to base your code around either all char&rsquo;s or long long&rsquo;s because this data type will always have the same size across machines. </p>
<p>Now, onto the &ldquo;check&rdquo;. If you read the above table carefully, you will come to know that most of the data type sizes can be misleading, i.e. they can be 32 bit even on 64 bit architectures. So, most people who make the mistake of using the size of integer on a machine for their checks fall into this trap.&nbsp;However, one of them that is useful for us is &ldquo;The Pointer&rdquo;. Yes, in all these models, the pointer to a data type is always 64 bit on 64 bit architectures and 32 bit on 32 bit architectures. Hence, the check becomes rather trivial, i.e.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">n <span style="color: #339933;">=</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span> <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The above expression results in n being equal to 8 on a 64 bit architecture and 4 on a 32 bit architecture. So, there it is but remember that should not try this out with function pointers because that can lead to wrong results but that is a topic for some other time. We&rsquo;ll bring you a few more articles about 32 bit vs 64 bit programming, its pitfalls, issues and areas where we can optimize and take advantage. Please let us know if you&rsquo;d like us to cover a certain aspect in particular.</p>
<p style='border:thin dotted black; padding:3mm;background-color: rgb(250,150,250);'>© <a href="http://www.safercode.com/blog/">Safer Code</a> | <a href="http://www.safercode.com/blog/2009/03/10/portable-code-how-to-check-if-a-machine-is-32-bit-or-64-bit.html">Portable Code: How To Check If A Machine Is 32 Bit Or 64 Bit</a></p>



Share and Enjoy:


	<a rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F03%2F10%2Fportable-code-how-to-check-if-a-machine-is-32-bit-or-64-bit.html&amp;title=Portable%20Code%3A%20How%20To%20Check%20If%20A%20Machine%20Is%2032%20Bit%20Or%2064%20Bit&amp;bodytext=Writing%20portable%20code%20is%20very%20important%20but%20it%20is%26nbsp%3Bone%20of%20the%20aspects%20that%20most%20people%20neglect%20until%20it%20is%20too%20late%20to%20realize%20its%20importance.%20Till%20few%20years%20ago%2C%20most%20people%20writing%20code%20for%20personal%20computers%20were%20not%20worried%20about%20the%20data%20siz" title="Digg"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F03%2F10%2Fportable-code-how-to-check-if-a-machine-is-32-bit-or-64-bit.html&amp;title=Portable%20Code%3A%20How%20To%20Check%20If%20A%20Machine%20Is%2032%20Bit%20Or%2064%20Bit&amp;notes=Writing%20portable%20code%20is%20very%20important%20but%20it%20is%26nbsp%3Bone%20of%20the%20aspects%20that%20most%20people%20neglect%20until%20it%20is%20too%20late%20to%20realize%20its%20importance.%20Till%20few%20years%20ago%2C%20most%20people%20writing%20code%20for%20personal%20computers%20were%20not%20worried%20about%20the%20data%20siz" title="del.icio.us"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F03%2F10%2Fportable-code-how-to-check-if-a-machine-is-32-bit-or-64-bit.html&amp;t=Portable%20Code%3A%20How%20To%20Check%20If%20A%20Machine%20Is%2032%20Bit%20Or%2064%20Bit" title="Facebook"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F03%2F10%2Fportable-code-how-to-check-if-a-machine-is-32-bit-or-64-bit.html&amp;title=Portable%20Code%3A%20How%20To%20Check%20If%20A%20Machine%20Is%2032%20Bit%20Or%2064%20Bit" title="StumbleUpon"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F03%2F10%2Fportable-code-how-to-check-if-a-machine-is-32-bit-or-64-bit.html&amp;title=Portable%20Code%3A%20How%20To%20Check%20If%20A%20Machine%20Is%2032%20Bit%20Or%2064%20Bit" title="Reddit"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.printfriendly.com/print?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F03%2F10%2Fportable-code-how-to-check-if-a-machine-is-32-bit-or-64-bit.html&amp;partner=sociable" title="Print this article!"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/printfriendly.png" title="Print this article!" alt="Print this article!" class="sociable-hovers" /></a>


<br/><br/>
	Tags: <a href="http://www.safercode.com/blog/tag/32bit" title="32&ndash;bit" rel="tag nofollow">32&ndash;bit</a>, <a href="http://www.safercode.com/blog/tag/64bit" title="64&ndash;bit" rel="tag nofollow">64&ndash;bit</a>, <a href="http://www.safercode.com/blog/tag/architectue" title="Architectue" rel="tag nofollow">Architectue</a>, <a href="http://www.safercode.com/blog/tag/c" title="C" rel="tag nofollow">C</a>, <a href="http://www.safercode.com/blog/tag/check-machine-64-bit" title="check machine 64 bit" rel="tag nofollow">check machine 64 bit</a>, <a href="http://www.safercode.com/blog/tag/cpp" title="CPP" rel="tag nofollow">CPP</a>, <a href="http://www.safercode.com/blog/tag/data-model" title="Data Model" rel="tag nofollow">Data Model</a>, <a href="http://www.safercode.com/blog/tag/data-models" title="data models" rel="tag nofollow">data models</a>, <a href="http://www.safercode.com/blog/tag/data-sizes" title="data sizes" rel="tag nofollow">data sizes</a>, <a href="http://www.safercode.com/blog/tag/data-types" title="data types" rel="tag nofollow">data types</a>, <a href="http://www.safercode.com/blog/tag/function-pointers" title="function pointers" rel="tag nofollow">function pointers</a>, <a href="http://www.safercode.com/blog/tag/hardware-architecture" title="Hardware Architecture" rel="tag nofollow">Hardware Architecture</a>, <a href="http://www.safercode.com/blog/tag/ilp32" title="ILP32" rel="tag nofollow">ILP32</a>, <a href="http://www.safercode.com/blog/tag/ilp64" title="ILP64" rel="tag nofollow">ILP64</a>, <a href="http://www.safercode.com/blog/tag/llp64" title="LLP64" rel="tag nofollow">LLP64</a>, <a href="http://www.safercode.com/blog/tag/lp32" title="LP32" rel="tag nofollow">LP32</a>, <a href="http://www.safercode.com/blog/tag/lp64" title="LP64" rel="tag nofollow">LP64</a>, <a href="http://www.safercode.com/blog/tag/pointers" title="pointers" rel="tag nofollow">pointers</a>, <a href="http://www.safercode.com/blog/tag/portable-code" title="Portable code" rel="tag nofollow">Portable code</a>, <a href="http://www.safercode.com/blog/tag/programming-model" title="Programming Model" rel="tag nofollow">Programming Model</a>, <a href="http://www.safercode.com/blog/tag/silp64" title="SILP64" rel="tag nofollow">SILP64</a>, <a href="http://www.safercode.com/blog/tag/writing-portable-code" title="writing portable code" rel="tag nofollow">writing portable code</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.safercode.com/blog/2009/02/24/volatile-c-keyword-myths-dispelled.html" title="Volatile: C Keyword Myths Dispelled (February 24, 2009)">Volatile: C Keyword Myths Dispelled</a> (12)</li>
	<li><a href="http://www.safercode.com/blog/2008/11/25/generic-function-pointers-in-c-and-void.html" title="Generic Function Pointers In C And Void * (November 25, 2008)">Generic Function Pointers In C And Void *</a> (5)</li>
	<li><a href="http://www.safercode.com/blog/2008/11/11/validating-untrusted-string-inputs.html" title="Validating Untrusted String Inputs (November 11, 2008)">Validating Untrusted String Inputs</a> (1)</li>
	<li><a href="http://www.safercode.com/blog/2008/10/21/validating-untrusted-integer-inputs.html" title="Validating Untrusted Integer Inputs (October 21, 2008)">Validating Untrusted Integer Inputs</a> (6)</li>
	<li><a href="http://www.safercode.com/blog/2008/12/02/unsafe-functions-in-c-and-their-safer-replacements-strings-part-ii.html" title="Unsafe Functions In C And Their Safer Replacements: Strings Part II (December 2, 2008)">Unsafe Functions In C And Their Safer Replacements: Strings Part II</a> (8)</li>
</ul>

<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/SaferCode?a=ralg1dUJXVM:-qAhh5WqcoA:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SaferCode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=ralg1dUJXVM:-qAhh5WqcoA:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=ralg1dUJXVM:-qAhh5WqcoA:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=ralg1dUJXVM:-qAhh5WqcoA:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=ralg1dUJXVM:-qAhh5WqcoA:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=ralg1dUJXVM:-qAhh5WqcoA:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=ralg1dUJXVM:-qAhh5WqcoA:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=ralg1dUJXVM:-qAhh5WqcoA:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=ralg1dUJXVM:-qAhh5WqcoA:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SaferCode/~4/ralg1dUJXVM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.safercode.com/blog/2009/03/10/portable-code-how-to-check-if-a-machine-is-32-bit-or-64-bit.html/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		<feedburner:origLink>http://www.safercode.com/blog/2009/03/10/portable-code-how-to-check-if-a-machine-is-32-bit-or-64-bit.html</feedburner:origLink></item>
		<item>
		<title>Volatile: C Keyword Myths Dispelled</title>
		<link>http://feedproxy.google.com/~r/SaferCode/~3/b9xGHvVQ3xE/volatile-c-keyword-myths-dispelled.html</link>
		<comments>http://www.safercode.com/blog/2009/02/24/volatile-c-keyword-myths-dispelled.html#comments</comments>
		<pubDate>Tue, 24 Feb 2009 14:00:00 +0000</pubDate>
		<dc:creator>Shantanu Goel</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Optimization]]></category>
		<category><![CDATA[-O2]]></category>
		<category><![CDATA[atomicity]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[const]]></category>
		<category><![CDATA[CPP]]></category>
		<category><![CDATA[gcc]]></category>
		<category><![CDATA[keyword]]></category>
		<category><![CDATA[memory barriers]]></category>
		<category><![CDATA[memory fences]]></category>
		<category><![CDATA[non-atomic access]]></category>
		<category><![CDATA[order of access]]></category>
		<category><![CDATA[volatile]]></category>
		<category><![CDATA[volatile keyword]]></category>

		<guid isPermaLink="false">http://www.safercode.com/blog/?p=33</guid>
		<description><![CDATA[<!-- Powered by Shantz WP Prefix Suffix. Tech Blog: http://tech.shantanugoel.com/ Secure Programming Blog: http://www.safercode.com/blog/ Blog: http://blog.shantanugoel.com/ -->Last time we explained the real meaning of const keyword, this time it&#8217;s going to be Volatile, the other sibling of this most misunderstood duo in C history. Let&#8217;s separate out the myths and the facts first and then we will discuss the how&#8217;s and why&#8217;s of it.
FACTS:

A volatile qualifier is important to be used [...]]]></description>
			<content:encoded><![CDATA[<!-- Powered by Shantz WP Prefix Suffix. Tech Blog: http://tech.shantanugoel.com/ Secure Programming Blog: http://www.safercode.com/blog/ Blog: http://blog.shantanugoel.com/ --><p style='border:thin dotted black; padding:3mm;background-color: rgb(250,150,250);'><strong><a href="http://feedproxy.google.com/SaferCode" rel="alternate" type="application/rss+xml">Subscribe To Our Feed</a> | <a href="http://twitter.com/safercode" rel="nofollow">Follow Us On Twitter</a> | <a href="http://feedburner.google.com/fb/a/mailverify?uri=safercode" rel="nofollow" target="_blank">Get Updates on Email</a></strong></p>
<p>Last time we explained the real meaning of <a title="C Keyword Const" href="http://www.safercode.com/blog/2009/02/04/const-keyword-explained.html" target="_blank" rel="me"><strong>const keyword</strong></a>, this time it&rsquo;s going to be <strong>Volatile</strong>, the other sibling of this most misunderstood duo in C history. Let&rsquo;s separate out the myths and the facts first and then we will discuss the how&rsquo;s and why&rsquo;s of it.</p>
<p><strong>FACTS:</strong></p>
<ul>
<li>A volatile qualifier is important to be used for auto-storage variables within setjmp and longjmp.</li>
<li>A volatile qualifier must be used when reading the contents of a memory location whose value can change unknown to the current program.</li>
<li>A volatile qualifier must be used for shared data modified in signal handlers or interrupt service routines.</li>
</ul>
<p><strong>MYTHS:</strong></p>
<ul>
<li>All shared data in multi-threaded programs must be declared volatile.</li>
</ul>
<p>Now, we&rsquo;ll see how we made the above classfication.</p>
<p>
<span id="more-33"></span><br />
The <em>only </em>information/directive that volatile keyword means to the compiler is to not apply any implementation specific optimization to the object to which this qualifier has been attached. e.g. One of the most general optimizations that a compiler can apply to a variable is that if it cannot find a variable&rsquo;s value being changed within a certain scope, it will cache the value of that variable, probably in a register, and then refer to that cached value whenever that variable is accessed instead of fetching it from the main memory.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &quot;stdio.h&quot;</span>
<span style="color: #339933;">#include &quot;setjmp.h&quot;</span>
<span style="color: #993333;">static</span> jmp_buf buf<span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #993333;">int</span> a<span style="color: #339933;">;</span>
  a <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>setjmp<span style="color: #009900;">&#40;</span>buf<span style="color: #009900;">&#41;</span><span style="color: #339933;">!=</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%d n&quot;</span><span style="color: #339933;">,</span> a<span style="color: #009900;">&#41;</span> <span style="color: #339933;">;</span>
    exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  a <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
  longjmp<span style="color: #009900;">&#40;</span>buf <span style="color: #339933;">,</span> <span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>If you were to compile the above program without any optimization, you would see the output as 1, which is correct. But if you were to compile it with optimization turned on (e.g. by using -O2 option with gcc), the output would be 0. This is because the compiler saw that &ldquo;a&rdquo; was not used after setting it to one and hence optimized out that statement. Then, if you try it out by declaring &ldquo;a&rdquo; as volatile, you&rsquo;d see the output as 1 even with optimization turned on, because the volatile qualifier would tell the compiler not to optimize any accesses related to a. For the 3 situations stated under facts, compiler cannot determine that a particular variable is needed or not because the accesses happen unknown to the compiler. Hence, we need to declare such variables as volatile.</p>
<p>Now, let&rsquo;s turn towards the myths. Many people say that since in multi-threaded environment, a shared variable&rsquo;s value can be changed by a thread before the other thread reads it, such variable should be declared as a volatile. But this is completely false. This is because a volatile qualifier just promises us that the accesses won&rsquo;t be optimized and would be read from main memory each time but a multi-threaded program needs much more, namely:</p>
<ol>
<li>Atomicity &ndash; The read/write access to the shared variables should be atomic in nature but access to volatile can be non-atomic and are completly implementation defined.</li>
<li>Preserve order of access &ndash; A volatile variable does not mandate this, especially when mixed with non-volatile variables.</li>
</ol>
<p>So, if you are writing a multi-threaded program, what you need is something that ensures these 2 particular things by providing you proper memory barriers. e.g. You could use mutexes, pthreads, or something similar that provides you the above mentioned semantics. </p>
<p>If you rely completely on volatile to get a proper working multi-threaded program for you, let me assure you that all you will achieve is introduce serious slowness to the program (by taking optimization out of the equation).&nbsp;e.g. nothing stops another thread from coming in changing your variable&rsquo;s value while you are half way through reading it in the current thread. And if you still require to use a volatile even after using a proper memory fencing &ldquo;lock&rdquo;, then there is something wrong with it and you need to take a hard look at your locking mechanism. But do not confuse it with the volatile provided in other languages like java where it does provide you with proper memory barriers.</p>
<p>I hope the article helped in clearing out your doubts about this mysterious little keyword from the C stable. Let us know if you have more questions about this.</p>
<p style='border:thin dotted black; padding:3mm;background-color: rgb(250,150,250);'>© <a href="http://www.safercode.com/blog/">Safer Code</a> | <a href="http://www.safercode.com/blog/2009/02/24/volatile-c-keyword-myths-dispelled.html">Volatile: C Keyword Myths Dispelled</a></p>



Share and Enjoy:


	<a rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F02%2F24%2Fvolatile-c-keyword-myths-dispelled.html&amp;title=Volatile%3A%20C%20Keyword%20Myths%20Dispelled&amp;bodytext=Last%20time%20we%20explained%20the%20real%20meaning%20of%20const%20keyword%2C%20this%20time%20it%26rsquo%3Bs%20going%20to%20be%20Volatile%2C%20the%20other%20sibling%20of%20this%20most%20misunderstood%20duo%20in%20C%20history.%20Let%26rsquo%3Bs%20separate%20out%20the%20myths%20and%20the%20facts%20first%20and%20then%20we%20will%20discuss%20the%20ho" title="Digg"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F02%2F24%2Fvolatile-c-keyword-myths-dispelled.html&amp;title=Volatile%3A%20C%20Keyword%20Myths%20Dispelled&amp;notes=Last%20time%20we%20explained%20the%20real%20meaning%20of%20const%20keyword%2C%20this%20time%20it%26rsquo%3Bs%20going%20to%20be%20Volatile%2C%20the%20other%20sibling%20of%20this%20most%20misunderstood%20duo%20in%20C%20history.%20Let%26rsquo%3Bs%20separate%20out%20the%20myths%20and%20the%20facts%20first%20and%20then%20we%20will%20discuss%20the%20ho" title="del.icio.us"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F02%2F24%2Fvolatile-c-keyword-myths-dispelled.html&amp;t=Volatile%3A%20C%20Keyword%20Myths%20Dispelled" title="Facebook"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F02%2F24%2Fvolatile-c-keyword-myths-dispelled.html&amp;title=Volatile%3A%20C%20Keyword%20Myths%20Dispelled" title="StumbleUpon"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F02%2F24%2Fvolatile-c-keyword-myths-dispelled.html&amp;title=Volatile%3A%20C%20Keyword%20Myths%20Dispelled" title="Reddit"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.printfriendly.com/print?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F02%2F24%2Fvolatile-c-keyword-myths-dispelled.html&amp;partner=sociable" title="Print this article!"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/printfriendly.png" title="Print this article!" alt="Print this article!" class="sociable-hovers" /></a>


<br/><br/>
	Tags: <a href="http://www.safercode.com/blog/tag/o2" title="-O2" rel="tag nofollow">-O2</a>, <a href="http://www.safercode.com/blog/tag/atomicity" title="atomicity" rel="tag nofollow">atomicity</a>, <a href="http://www.safercode.com/blog/tag/c" title="C" rel="tag nofollow">C</a>, <a href="http://www.safercode.com/blog/tag/const" title="const" rel="tag nofollow">const</a>, <a href="http://www.safercode.com/blog/tag/cpp" title="CPP" rel="tag nofollow">CPP</a>, <a href="http://www.safercode.com/blog/tag/gcc" title="gcc" rel="tag nofollow">gcc</a>, <a href="http://www.safercode.com/blog/tag/keyword" title="keyword" rel="tag nofollow">keyword</a>, <a href="http://www.safercode.com/blog/tag/memory-barriers" title="memory barriers" rel="tag nofollow">memory barriers</a>, <a href="http://www.safercode.com/blog/tag/memory-fences" title="memory fences" rel="tag nofollow">memory fences</a>, <a href="http://www.safercode.com/blog/tag/non-atomic-access" title="non-atomic access" rel="tag nofollow">non-atomic access</a>, <a href="http://www.safercode.com/blog/tag/optimization" title="Optimization" rel="tag nofollow">Optimization</a>, <a href="http://www.safercode.com/blog/tag/order-of-access" title="order of access" rel="tag nofollow">order of access</a>, <a href="http://www.safercode.com/blog/tag/volatile" title="volatile" rel="tag nofollow">volatile</a>, <a href="http://www.safercode.com/blog/tag/volatile-keyword" title="volatile keyword" rel="tag nofollow">volatile keyword</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.safercode.com/blog/2009/02/04/const-keyword-explained.html" title="&quot;const&quot; Keyword Explained (February 4, 2009)">&quot;const&quot; Keyword Explained</a> (17)</li>
	<li><a href="http://www.safercode.com/blog/2009/01/27/tweak-your-code-for-speed-unroll-those-loops-part-1.html" title="Tweak Your Code For Speed: Unroll Those Loops Part 1 (January 27, 2009)">Tweak Your Code For Speed: Unroll Those Loops Part 1</a> (5)</li>
	<li><a href="http://www.safercode.com/blog/2009/03/10/portable-code-how-to-check-if-a-machine-is-32-bit-or-64-bit.html" title="Portable Code: How To Check If A Machine Is 32 Bit Or 64 Bit (March 10, 2009)">Portable Code: How To Check If A Machine Is 32 Bit Or 64 Bit</a> (9)</li>
	<li><a href="http://www.safercode.com/blog/2008/10/28/optimizing-switch-case-statements-in-c-for-speed.html" title="Optimizing Switch-Case Statements In C For Speed (October 28, 2008)">Optimizing Switch-Case Statements In C For Speed</a> (11)</li>
	<li><a href="http://www.safercode.com/blog/2008/10/14/and-so-it-begins.html" title="And So It Begins&#8230; (October 14, 2008)">And So It Begins&#8230;</a> (0)</li>
</ul>

<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/SaferCode?a=b9xGHvVQ3xE:O3ArqXy6Ers:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SaferCode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=b9xGHvVQ3xE:O3ArqXy6Ers:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=b9xGHvVQ3xE:O3ArqXy6Ers:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=b9xGHvVQ3xE:O3ArqXy6Ers:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=b9xGHvVQ3xE:O3ArqXy6Ers:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=b9xGHvVQ3xE:O3ArqXy6Ers:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=b9xGHvVQ3xE:O3ArqXy6Ers:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=b9xGHvVQ3xE:O3ArqXy6Ers:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=b9xGHvVQ3xE:O3ArqXy6Ers:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SaferCode/~4/b9xGHvVQ3xE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.safercode.com/blog/2009/02/24/volatile-c-keyword-myths-dispelled.html/feed</wfw:commentRss>
		<slash:comments>12</slash:comments>
		<feedburner:origLink>http://www.safercode.com/blog/2009/02/24/volatile-c-keyword-myths-dispelled.html</feedburner:origLink></item>
		<item>
		<title>Predicting the rand() and using Cryptographic Random Numbers</title>
		<link>http://feedproxy.google.com/~r/SaferCode/~3/gpZH6WaUSPc/predicting-the-rand-and-using-cryptographic-random-numbers.html</link>
		<comments>http://www.safercode.com/blog/2009/02/10/predicting-the-rand-and-using-cryptographic-random-numbers.html#comments</comments>
		<pubDate>Tue, 10 Feb 2009 16:08:19 +0000</pubDate>
		<dc:creator>Amit Goel</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Concepts]]></category>
		<category><![CDATA[CryptGenRandom]]></category>
		<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Efficiency]]></category>
		<category><![CDATA[rand]]></category>
		<category><![CDATA[Random Numbers]]></category>
		<category><![CDATA[security holes]]></category>

		<guid isPermaLink="false">http://www.safercode.com/blog/?p=31</guid>
		<description><![CDATA[<!-- Powered by Shantz WP Prefix Suffix. Tech Blog: http://tech.shantanugoel.com/ Secure Programming Blog: http://www.safercode.com/blog/ Blog: http://blog.shantanugoel.com/ -->Everyone must have used rand() sometime or the other while writing C code. The problem with rand() in most of the platforms is that it is easy to predict the output. Being based on unsigned int, it is just a simple function using a seed which is always the last randomly generated some number. This [...]]]></description>
			<content:encoded><![CDATA[<!-- Powered by Shantz WP Prefix Suffix. Tech Blog: http://tech.shantanugoel.com/ Secure Programming Blog: http://www.safercode.com/blog/ Blog: http://blog.shantanugoel.com/ --><p style='border:thin dotted black; padding:3mm;background-color: rgb(250,150,250);'><strong><a href="http://feedproxy.google.com/SaferCode" rel="alternate" type="application/rss+xml">Subscribe To Our Feed</a> | <a href="http://twitter.com/safercode" rel="nofollow">Follow Us On Twitter</a> | <a href="http://feedburner.google.com/fb/a/mailverify?uri=safercode" rel="nofollow" target="_blank">Get Updates on Email</a></strong></p>
<p>Everyone must have used rand() sometime or the other while writing C code. The problem with rand() in most of the platforms is that it is easy to predict the output. Being based on <em>unsigned int</em>, it is just a simple function using a seed which is always the last randomly generated some number. This seed is not very tough to guess for an advanced hacker. once this seed is guessed,, any password or information based on random number generation can be easilt cracked and maligned.</p>
<p>following code is abridged code of rand() function implementation referenced from the book <em>The C programming Language written by Brian Kernighan and Dennis Ritchie </em></p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">unsigned</span> <span style="color: #993333;">long</span> <span style="color: #993333;">int</span> next <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> rand<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    next <span style="color: #339933;">=</span> next <span style="color: #339933;">*</span> <span style="color: #0000dd;">1103515245</span> <span style="color: #339933;">+</span> <span style="color: #0000dd;">12345</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span>next <span style="color: #339933;">/</span> <span style="color: #0000dd;">65536</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> <span style="color: #0000dd;">32768</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This type of function is generally called <em>linear congruential function</em>. As you can notice yourself, that these type of linear congruential functions are very much predictable and are not recommended for security sensitive applications. If you look at the above given code, it is obvious that if the underlying environment does not change, then the random number generation can easily be guessed as it will generate same random number on running the application again and again.</p>
<p>
<span id="more-31"></span></p>
<p>Any type of good random number generator should adhere to three basic properties:</p>
<ol>
<li>Generate evenly distributed numbers</li>
<li>The generated number should be unpredictable</li>
<li>It should use a long cycle of range of numbers</li>
</ol>
<p>Linear congruential functions just suffice the first property but fail miserably in the other two, thus, making themselves unusable for secure random number generation.In the early era of internet, people have used the rand() function, and hackers have exploited it at leisure.</p>
<p>To Solve this problem, most of the platforms support Cryptographic Random Numbers these days. For example, CryptGenRandom is provided by almost all the Windows platforms. These type of Cryptographic Random numbers are completely random as the seed used in them is also unknown to the programmer. It is completely random because it uses the system properties(system entropy) to generate the seed, which is then hashed used a hashing algorithm like SHA-1/MD4/MD5 etc. This implementation is completely platform dependent. For example: quite a few parameters used by Windows platforms are like</p>
<ol>
<li>Current Process ID</li>
<li>Current Thread ID</li>
<li>GetLocalTime()</li>
<li>CPU counters</li>
<li>Allocated Process Memmory at initial time</li>
<li>Page Fault count</li>
<li>etc etc etc&#8230;.</li>
</ol>
<p>Due to these large number of parameters and then, applying the hashing algorithms, the seed becomes almost random and unpredictable, thus, making it next to impossible to be decrypted.</p>
<p>Crypt Random Numbers and algorithms are part of FIPS (Federal Information Processing Standard) standard. The above mentioned function is a part of FIPS 186-2 standard.</p>
<p>Talking about Cryptographic Random numbers is a fairly vast topic and I would like to continue in my next post.
<p style='border:thin dotted black; padding:3mm;background-color: rgb(250,150,250);'>© <a href="http://www.safercode.com/blog/">Safer Code</a> | <a href="http://www.safercode.com/blog/2009/02/10/predicting-the-rand-and-using-cryptographic-random-numbers.html">Predicting the rand() and using Cryptographic Random Numbers</a></p>



Share and Enjoy:


	<a rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F02%2F10%2Fpredicting-the-rand-and-using-cryptographic-random-numbers.html&amp;title=Predicting%20the%20rand%28%29%20and%20using%20Cryptographic%20Random%20Numbers&amp;bodytext=Everyone%20must%20have%20used%20rand%28%29%20sometime%20or%20the%20other%20while%20writing%20C%20code.%20The%20problem%20with%20rand%28%29%20in%20most%20of%20the%20platforms%20is%20that%20it%20is%20easy%20to%20predict%20the%20output.%20Being%20based%20on%20unsigned%20int%2C%20it%20is%20just%20a%20simple%20function%20using%20a%20seed%20which%20is%20alwa" title="Digg"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F02%2F10%2Fpredicting-the-rand-and-using-cryptographic-random-numbers.html&amp;title=Predicting%20the%20rand%28%29%20and%20using%20Cryptographic%20Random%20Numbers&amp;notes=Everyone%20must%20have%20used%20rand%28%29%20sometime%20or%20the%20other%20while%20writing%20C%20code.%20The%20problem%20with%20rand%28%29%20in%20most%20of%20the%20platforms%20is%20that%20it%20is%20easy%20to%20predict%20the%20output.%20Being%20based%20on%20unsigned%20int%2C%20it%20is%20just%20a%20simple%20function%20using%20a%20seed%20which%20is%20alwa" title="del.icio.us"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F02%2F10%2Fpredicting-the-rand-and-using-cryptographic-random-numbers.html&amp;t=Predicting%20the%20rand%28%29%20and%20using%20Cryptographic%20Random%20Numbers" title="Facebook"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F02%2F10%2Fpredicting-the-rand-and-using-cryptographic-random-numbers.html&amp;title=Predicting%20the%20rand%28%29%20and%20using%20Cryptographic%20Random%20Numbers" title="StumbleUpon"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F02%2F10%2Fpredicting-the-rand-and-using-cryptographic-random-numbers.html&amp;title=Predicting%20the%20rand%28%29%20and%20using%20Cryptographic%20Random%20Numbers" title="Reddit"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.printfriendly.com/print?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F02%2F10%2Fpredicting-the-rand-and-using-cryptographic-random-numbers.html&amp;partner=sociable" title="Print this article!"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/printfriendly.png" title="Print this article!" alt="Print this article!" class="sociable-hovers" /></a>


<br/><br/>
	Tags: <a href="http://www.safercode.com/blog/tag/c" title="C" rel="tag nofollow">C</a>, <a href="http://www.safercode.com/blog/tag/concepts" title="Concepts" rel="tag nofollow">Concepts</a>, <a href="http://www.safercode.com/blog/tag/cryptgenrandom" title="CryptGenRandom" rel="tag nofollow">CryptGenRandom</a>, <a href="http://www.safercode.com/blog/tag/cryptography" title="Cryptography" rel="tag nofollow">Cryptography</a>, <a href="http://www.safercode.com/blog/tag/efficiency" title="Efficiency" rel="tag nofollow">Efficiency</a>, <a href="http://www.safercode.com/blog/tag/rand" title="rand" rel="tag nofollow">rand</a>, <a href="http://www.safercode.com/blog/tag/random-numbers" title="Random Numbers" rel="tag nofollow">Random Numbers</a>, <a href="http://www.safercode.com/blog/tag/security" title="Security" rel="tag nofollow">Security</a>, <a href="http://www.safercode.com/blog/tag/security-holes" title="security holes" rel="tag nofollow">security holes</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.safercode.com/blog/2008/10/14/and-so-it-begins.html" title="And So It Begins&#8230; (October 14, 2008)">And So It Begins&#8230;</a> (0)</li>
	<li><a href="http://www.safercode.com/blog/2008/11/18/all-input-is-evil.html" title="All Input is Evil (November 18, 2008)">All Input is Evil</a> (3)</li>
	<li><a href="http://www.safercode.com/blog/2008/12/16/using-enum-pattern-in-java-15.html" title="Using Enum Pattern in Java < 1.5 (December 16, 2008)">Using Enum Pattern in Java < 1.5</a> (1)</li>
	<li><a href="http://www.safercode.com/blog/2009/01/13/improper-variable-initialization.html" title="Improper Variable Initialization (January 13, 2009)">Improper Variable Initialization</a> (0)</li>
	<li><a href="http://www.safercode.com/blog/2009/06/10/de-bugging-code-before-check-in.html" title="&#8220;De-Bugging&#8221; Code before Check-in (June 10, 2009)">&#8220;De-Bugging&#8221; Code before Check-in</a> (0)</li>
</ul>

<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/SaferCode?a=gpZH6WaUSPc:njHtoWWGX9Q:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SaferCode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=gpZH6WaUSPc:njHtoWWGX9Q:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=gpZH6WaUSPc:njHtoWWGX9Q:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=gpZH6WaUSPc:njHtoWWGX9Q:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=gpZH6WaUSPc:njHtoWWGX9Q:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=gpZH6WaUSPc:njHtoWWGX9Q:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=gpZH6WaUSPc:njHtoWWGX9Q:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=gpZH6WaUSPc:njHtoWWGX9Q:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=gpZH6WaUSPc:njHtoWWGX9Q:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SaferCode/~4/gpZH6WaUSPc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.safercode.com/blog/2009/02/10/predicting-the-rand-and-using-cryptographic-random-numbers.html/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<feedburner:origLink>http://www.safercode.com/blog/2009/02/10/predicting-the-rand-and-using-cryptographic-random-numbers.html</feedburner:origLink></item>
		<item>
		<title>"const" Keyword Explained</title>
		<link>http://feedproxy.google.com/~r/SaferCode/~3/bTcu13EvFXQ/const-keyword-explained.html</link>
		<comments>http://www.safercode.com/blog/2009/02/04/const-keyword-explained.html#comments</comments>
		<pubDate>Tue, 03 Feb 2009 18:30:00 +0000</pubDate>
		<dc:creator>Shantanu Goel</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[compiler]]></category>
		<category><![CDATA[const]]></category>
		<category><![CDATA[keyword]]></category>
		<category><![CDATA[Optimization]]></category>
		<category><![CDATA[read only]]></category>
		<category><![CDATA[volatile]]></category>

		<guid isPermaLink="false">http://www.safercode.com/blog/2009/02/04/const-keyword-explained.html</guid>
		<description><![CDATA[<!-- Powered by Shantz WP Prefix Suffix. Tech Blog: http://tech.shantanugoel.com/ Secure Programming Blog: http://www.safercode.com/blog/ Blog: http://blog.shantanugoel.com/ -->There are a few very basic things in C that are widely misunderstood by programmers of all caders. This is not because these things are very complex, but because books and teachers do not give them their due importance while teaching beginners and the misconceptions stick even years later. A few of these are like [...]]]></description>
			<content:encoded><![CDATA[<!-- Powered by Shantz WP Prefix Suffix. Tech Blog: http://tech.shantanugoel.com/ Secure Programming Blog: http://www.safercode.com/blog/ Blog: http://blog.shantanugoel.com/ --><p style='border:thin dotted black; padding:3mm;background-color: rgb(250,150,250);'><strong><a href="http://feedproxy.google.com/SaferCode" rel="alternate" type="application/rss+xml">Subscribe To Our Feed</a> | <a href="http://twitter.com/safercode" rel="nofollow">Follow Us On Twitter</a> | <a href="http://feedburner.google.com/fb/a/mailverify?uri=safercode" rel="nofollow" target="_blank">Get Updates on Email</a></strong></p>
<p>There are a few very basic things in C that are widely misunderstood by programmers of all caders. This is not because these things are very complex, but because books and teachers do not give them their due importance while teaching beginners and the misconceptions stick even years later. A few of these are like the keywords “volatile” (covered in next post) and “const”.</p>
<p>Look at the following piece of code:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
<span style="color: #993333;">const</span> <span style="color: #993333;">int</span> a <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
a <span style="color: #339933;">=</span> <span style="color: #0000dd;">2</span><span style="color: #339933;">;</span>
<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> a<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>You’d be quick to point out (correctly) that the above code wouldn’t compile. It would fail with an error on the lines of “assignment of read-only variable a” because a is now a “constant” because of the const type qualifier attached to it. And now comes the issue. Many start assuming (or might even be explicitly taught) that the value of a cannot be changed now. Did you think so too? Well, you thought wrong. Look at the following code:</p>
<p><span id="more-29"></span></p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
<span style="color: #993333;">const</span> <span style="color: #993333;">int</span> a <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> <span style="color: #339933;">*</span>b <span style="color: #339933;">=</span> <span style="color: #339933;">&amp;</span>a<span style="color: #339933;">;</span>
<span style="color: #339933;">*</span>b <span style="color: #339933;">=</span> <span style="color: #0000dd;">2</span><span style="color: #339933;">;</span>
<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%d %d&quot;</span><span style="color: #339933;">,</span> a<span style="color: #339933;">,</span> <span style="color: #339933;">*</span>b<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Now, this program will compile (with a warning though, which can be removed by typecasting &amp;a to int*) and will print the output as …any guesses? Well, lets see this “output” part later below. But how did that compilation go through?</p>
<p>Basically, by qualifying a variable as const, you are getting a gaurantee from the compiler that the value of that memory location cannot be changed “through that name” but can still be changed by any external program or even with the same program through another name.</p>
<p>But the story just doesn’t stop there. Some would say that this is impossible because by when you declare something as const, the compiler will put it in read only memory. This might be true or might not be because it is not specified in the C standard and is totally implementation dependent.</p>
<p>Now, lets come back to the “output” part, as in what actually would be printed on the console. Well, it could be anything because the C standard states that:</p>
<blockquote>
<p>If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.</p>
</blockquote>
<p dir="ltr">So, you’d be lucky if your computer doesn’t grow a tail and starts dancing drunk to the tune of a wild african native song <img src='http://www.safercode.com/blog/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> . So, you could see the output as “1 1” or “2 2” with the most interesting one being “1 2”. Woah, how did that happen. It’s simple actually and if you were to see such an output, just assemble the code instead of compiling and see the assembly listing. I’ll explaing the reason here with a bit of background. Basically, there are 2 important uses of const keyword in programming:</p>
<ol dir="ltr">
<li>
<div>To stop the programmer from mistakenly overwriting some data (e.g. a utility function that just compares 2 strings doesn’t need to modify them).</div>
</li>
<li>
<div>To allow the compiler to optimize the code for performance when you know for sure that the value of a variable would not change.</div>
</li>
</ol>
<p>So, the “weird” output you see might be an outcome of the 2nd point above. Since you are telling the compiler that the variable is “read only”, it can optimize accesses to it in many ways, 2 of which are listed below:</p>
<ol>
<li>
<div>It caches the variable’s value into a register and even though the write access to a through *b actually modifies the content of memory pointed to by a, the read access while printing the value of a still gets it from the register.</div>
</li>
<li>
<div>It could even replace the variable “a” by a constant value “1” anywhere it is used in the program.</div>
</li>
</ol>
<p>So, there we go. I hope now you fully understand the concept behind the “const” keyword. I’ll take up even more infamous “volatile” next time. Do write in with your queries.</p>
<p style='border:thin dotted black; padding:3mm;background-color: rgb(250,150,250);'>© <a href="http://www.safercode.com/blog/">Safer Code</a> | <a href="http://www.safercode.com/blog/2009/02/04/const-keyword-explained.html">&quot;const&quot; Keyword Explained</a></p>



Share and Enjoy:


	<a rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F02%2F04%2Fconst-keyword-explained.html&amp;title=%26quot%3Bconst%26quot%3B%20Keyword%20Explained&amp;bodytext=There%20are%20a%20few%20very%20basic%20things%20in%20C%20that%20are%20widely%20misunderstood%20by%20programmers%20of%20all%20caders.%20This%20is%20not%20because%20these%20things%20are%20very%20complex%2C%20but%20because%20books%20and%20teachers%20do%20not%20give%20them%20their%20due%20importance%20while%20teaching%20beginners%20and%20th" title="Digg"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F02%2F04%2Fconst-keyword-explained.html&amp;title=%26quot%3Bconst%26quot%3B%20Keyword%20Explained&amp;notes=There%20are%20a%20few%20very%20basic%20things%20in%20C%20that%20are%20widely%20misunderstood%20by%20programmers%20of%20all%20caders.%20This%20is%20not%20because%20these%20things%20are%20very%20complex%2C%20but%20because%20books%20and%20teachers%20do%20not%20give%20them%20their%20due%20importance%20while%20teaching%20beginners%20and%20th" title="del.icio.us"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F02%2F04%2Fconst-keyword-explained.html&amp;t=%26quot%3Bconst%26quot%3B%20Keyword%20Explained" title="Facebook"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F02%2F04%2Fconst-keyword-explained.html&amp;title=%26quot%3Bconst%26quot%3B%20Keyword%20Explained" title="StumbleUpon"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F02%2F04%2Fconst-keyword-explained.html&amp;title=%26quot%3Bconst%26quot%3B%20Keyword%20Explained" title="Reddit"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.printfriendly.com/print?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F02%2F04%2Fconst-keyword-explained.html&amp;partner=sociable" title="Print this article!"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/printfriendly.png" title="Print this article!" alt="Print this article!" class="sociable-hovers" /></a>


<br/><br/>
	Tags: <a href="http://www.safercode.com/blog/tag/c" title="C" rel="tag nofollow">C</a>, <a href="http://www.safercode.com/blog/tag/compiler" title="compiler" rel="tag nofollow">compiler</a>, <a href="http://www.safercode.com/blog/tag/const" title="const" rel="tag nofollow">const</a>, <a href="http://www.safercode.com/blog/tag/keyword" title="keyword" rel="tag nofollow">keyword</a>, <a href="http://www.safercode.com/blog/tag/optimization" title="Optimization" rel="tag nofollow">Optimization</a>, <a href="http://www.safercode.com/blog/tag/read-only" title="read only" rel="tag nofollow">read only</a>, <a href="http://www.safercode.com/blog/tag/volatile" title="volatile" rel="tag nofollow">volatile</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.safercode.com/blog/2009/02/24/volatile-c-keyword-myths-dispelled.html" title="Volatile: C Keyword Myths Dispelled (February 24, 2009)">Volatile: C Keyword Myths Dispelled</a> (12)</li>
	<li><a href="http://www.safercode.com/blog/2009/01/27/tweak-your-code-for-speed-unroll-those-loops-part-1.html" title="Tweak Your Code For Speed: Unroll Those Loops Part 1 (January 27, 2009)">Tweak Your Code For Speed: Unroll Those Loops Part 1</a> (5)</li>
	<li><a href="http://www.safercode.com/blog/2008/10/28/optimizing-switch-case-statements-in-c-for-speed.html" title="Optimizing Switch-Case Statements In C For Speed (October 28, 2008)">Optimizing Switch-Case Statements In C For Speed</a> (11)</li>
	<li><a href="http://www.safercode.com/blog/2008/10/14/and-so-it-begins.html" title="And So It Begins&#8230; (October 14, 2008)">And So It Begins&#8230;</a> (0)</li>
	<li><a href="http://www.safercode.com/blog/2008/11/11/validating-untrusted-string-inputs.html" title="Validating Untrusted String Inputs (November 11, 2008)">Validating Untrusted String Inputs</a> (1)</li>
</ul>

<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/SaferCode?a=bTcu13EvFXQ:h5FV9KVVYCI:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SaferCode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=bTcu13EvFXQ:h5FV9KVVYCI:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=bTcu13EvFXQ:h5FV9KVVYCI:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=bTcu13EvFXQ:h5FV9KVVYCI:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=bTcu13EvFXQ:h5FV9KVVYCI:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=bTcu13EvFXQ:h5FV9KVVYCI:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=bTcu13EvFXQ:h5FV9KVVYCI:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=bTcu13EvFXQ:h5FV9KVVYCI:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=bTcu13EvFXQ:h5FV9KVVYCI:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SaferCode/~4/bTcu13EvFXQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.safercode.com/blog/2009/02/04/const-keyword-explained.html/feed</wfw:commentRss>
		<slash:comments>17</slash:comments>
		<feedburner:origLink>http://www.safercode.com/blog/2009/02/04/const-keyword-explained.html</feedburner:origLink></item>
		<item>
		<title>Tweak Your Code For Speed: Unroll Those Loops Part 1</title>
		<link>http://feedproxy.google.com/~r/SaferCode/~3/-cwyOMimf5o/tweak-your-code-for-speed-unroll-those-loops-part-1.html</link>
		<comments>http://www.safercode.com/blog/2009/01/27/tweak-your-code-for-speed-unroll-those-loops-part-1.html#comments</comments>
		<pubDate>Tue, 27 Jan 2009 13:40:23 +0000</pubDate>
		<dc:creator>Shantanu Goel</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Optimization]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[iterations]]></category>
		<category><![CDATA[Loop Unrolling]]></category>
		<category><![CDATA[Loops]]></category>
		<category><![CDATA[Optimization techniques]]></category>
		<category><![CDATA[Pipelining]]></category>

		<guid isPermaLink="false">http://www.safercode.com/blog/?p=15</guid>
		<description><![CDATA[<!-- Powered by Shantz WP Prefix Suffix. Tech Blog: http://tech.shantanugoel.com/ Secure Programming Blog: http://www.safercode.com/blog/ Blog: http://blog.shantanugoel.com/ -->One of the ways to optimize your code for speed is to unroll the loops you have in your program. If you don&#8217;t know what loop unrolling is, then see the following simple example, where we are trying to copy a 5 element long string:
A Simple Loop:

for &#40;i = 0 ; i &#60; 5; ++i&#41;
&#123;
 [...]]]></description>
			<content:encoded><![CDATA[<!-- Powered by Shantz WP Prefix Suffix. Tech Blog: http://tech.shantanugoel.com/ Secure Programming Blog: http://www.safercode.com/blog/ Blog: http://blog.shantanugoel.com/ --><p style='border:thin dotted black; padding:3mm;background-color: rgb(250,150,250);'><strong><a href="http://feedproxy.google.com/SaferCode" rel="alternate" type="application/rss+xml">Subscribe To Our Feed</a> | <a href="http://twitter.com/safercode" rel="nofollow">Follow Us On Twitter</a> | <a href="http://feedburner.google.com/fb/a/mailverify?uri=safercode" rel="nofollow" target="_blank">Get Updates on Email</a></strong></p>
<p>One of the ways to optimize your code for speed is to unroll the loops you have in your program. If you don&#8217;t know what loop unrolling is, then see the following simple example, where we are trying to copy a 5 element long string:<br />
A Simple Loop:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span> <span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">5</span><span style="color: #339933;">;</span> <span style="color: #339933;">++</span>i<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #339933;">*</span>j<span style="color: #339933;">++</span> <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>k<span style="color: #339933;">++;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The same loop unrolled:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">*</span>j<span style="color: #339933;">++</span> <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>k<span style="color: #339933;">++;</span>
<span style="color: #339933;">*</span>j<span style="color: #339933;">++</span> <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>k<span style="color: #339933;">++;</span>
<span style="color: #339933;">*</span>j<span style="color: #339933;">++</span> <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>k<span style="color: #339933;">++;</span>
<span style="color: #339933;">*</span>j<span style="color: #339933;">++</span> <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>k<span style="color: #339933;">++;</span>
<span style="color: #339933;">*</span>j<span style="color: #339933;">++</span> <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>k<span style="color: #339933;">++;</span></pre></div></div>

<p>Now, the unrolled version is definitely going to be faster because of the following reasons:</p>
<p>1. There are no branches any more. In a loop, the compiler has to insert branches to jump back to the for statement.</p>
<p>2. There are no condition checks. In a loop, the value of i is checked every time to see what to do next.</p>
<p>3. A third rather hidden, but really important, advantage is that unrolled code can be pipelined efficiently by the processor hence resulting in faster execution.</p>
<p>The above code in itself might not show you any perceivable difference in execution time, but it does become crucial when the loops are of much higher magnitude and especially in embedded/real time scenarios.</p>
<p>Now, the loop unrolling can be done by the compiler or manually by the coder. In this part, we will see how to facilitate compiler to carry out loop unrolling efficiently.<span id="more-15"></span></p>
<p>1. Turn on your compiler&#8217;s optimization switches.</p>
<p>2. Find out if there are any pragmas available through which you can pass additional information to the compiler to help it in unrolling the loops. This information could be in the form of minimum no. of times the loop will be executed, maximum number of times the loop will be executed, is the number of times the loop will be executed a multiple of some particular number, etc. How this information helps the compiler will become clear in the next part of this series when we will tell you how to manually unroll the loops.</p>
<p>3. Try to keep the loop implementation in such a way that the variables written in one iteration are not read in the future iterations. e.g. in the above example, the variable &#8220;i&#8221; should not be modified within the loop. This would ensure that any given iteration of a loop is independent of the past values of i and hence can be easily pipelined.</p>
<p>4. Try to take out epilog and prolog from the loop. This refers to the statements which are not executed on every iteration of the loop but only at the starting or at the end of the loop. e.g. see the following example:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">5</span><span style="color: #339933;">;</span> <span style="color: #339933;">++</span>i<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
         <span style="color: #339933;">*</span>j<span style="color: #339933;">++</span> <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>w<span style="color: #339933;">;</span>
         <span style="color: #b1b100;">continue</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #339933;">*</span>j<span style="color: #339933;">++</span> <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>k<span style="color: #339933;">++;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>In this code, when i is 0, we carry out some special code. This could be rewritten as:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">*</span>j<span style="color: #339933;">++</span> <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>w<span style="color: #339933;">;</span>
<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">4</span><span style="color: #339933;">;</span> <span style="color: #339933;">++</span>i<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #339933;">*</span>j<span style="color: #339933;">++</span> <span style="color: #339933;">=</span> <span style="color: #339933;">*</span>k<span style="color: #339933;">++;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>5. Keep the loop body small, if you want to reap the benefits of pipelining. Many people might tell you to group the code that is executed same number of times into a single loop. But I&#8217;d say that if the 2 piecs of code are unrelated, it is better to keep them separate in 2 different loops in your c code. Because this will not affect the compiler from unrolling them (rather might help it in doing this, actually) but also allow it pipeline your code efficiently.</p>
<p>6. Try not to have external branches (like goto, function calls, etc) in your loop body. This also helps the compiler in pipelining the code.</p>
<p>7. The last advice is to avoid nested loops. Because in nested loops, the compiler will unroll only the outer loops, leaving the inner loops untouched. If you can&#8217;t avoid such conditions, it is generally recommended that you unroll the inner loops manually.</p>
<p>This is it, for this time. We will talk about manual loop unrolling next week. Let us know your queries and comments, and also about what topics should would like to know about next.
<p style='border:thin dotted black; padding:3mm;background-color: rgb(250,150,250);'>© <a href="http://www.safercode.com/blog/">Safer Code</a> | <a href="http://www.safercode.com/blog/2009/01/27/tweak-your-code-for-speed-unroll-those-loops-part-1.html">Tweak Your Code For Speed: Unroll Those Loops Part 1</a></p>



Share and Enjoy:


	<a rel="nofollow" target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F01%2F27%2Ftweak-your-code-for-speed-unroll-those-loops-part-1.html&amp;title=Tweak%20Your%20Code%20For%20Speed%3A%20Unroll%20Those%20Loops%20Part%201&amp;bodytext=One%20of%20the%20ways%20to%20optimize%20your%20code%20for%20speed%20is%20to%20unroll%20the%20loops%20you%20have%20in%20your%20program.%20If%20you%20don%27t%20know%20what%20loop%20unrolling%20is%2C%20then%20see%20the%20following%20simple%20example%2C%20where%20we%20are%20trying%20to%20copy%20a%205%20element%20long%20string%3A%0D%0AA%20Simple%20Loop%3A%0D%0Afo" title="Digg"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F01%2F27%2Ftweak-your-code-for-speed-unroll-those-loops-part-1.html&amp;title=Tweak%20Your%20Code%20For%20Speed%3A%20Unroll%20Those%20Loops%20Part%201&amp;notes=One%20of%20the%20ways%20to%20optimize%20your%20code%20for%20speed%20is%20to%20unroll%20the%20loops%20you%20have%20in%20your%20program.%20If%20you%20don%27t%20know%20what%20loop%20unrolling%20is%2C%20then%20see%20the%20following%20simple%20example%2C%20where%20we%20are%20trying%20to%20copy%20a%205%20element%20long%20string%3A%0D%0AA%20Simple%20Loop%3A%0D%0Afo" title="del.icio.us"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F01%2F27%2Ftweak-your-code-for-speed-unroll-those-loops-part-1.html&amp;t=Tweak%20Your%20Code%20For%20Speed%3A%20Unroll%20Those%20Loops%20Part%201" title="Facebook"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F01%2F27%2Ftweak-your-code-for-speed-unroll-those-loops-part-1.html&amp;title=Tweak%20Your%20Code%20For%20Speed%3A%20Unroll%20Those%20Loops%20Part%201" title="StumbleUpon"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F01%2F27%2Ftweak-your-code-for-speed-unroll-those-loops-part-1.html&amp;title=Tweak%20Your%20Code%20For%20Speed%3A%20Unroll%20Those%20Loops%20Part%201" title="Reddit"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" class="sociable-hovers" /></a>
	<a rel="nofollow" target="_blank" href="http://www.printfriendly.com/print?url=http%3A%2F%2Fwww.safercode.com%2Fblog%2F2009%2F01%2F27%2Ftweak-your-code-for-speed-unroll-those-loops-part-1.html&amp;partner=sociable" title="Print this article!"><img src="http://www.safercode.com/blog/wp-content/plugins/sociable/images/printfriendly.png" title="Print this article!" alt="Print this article!" class="sociable-hovers" /></a>


<br/><br/>
	Tags: <a href="http://www.safercode.com/blog/tag/c" title="C" rel="tag nofollow">C</a>, <a href="http://www.safercode.com/blog/tag/iterations" title="iterations" rel="tag nofollow">iterations</a>, <a href="http://www.safercode.com/blog/tag/loop-unrolling" title="Loop Unrolling" rel="tag nofollow">Loop Unrolling</a>, <a href="http://www.safercode.com/blog/tag/loops" title="Loops" rel="tag nofollow">Loops</a>, <a href="http://www.safercode.com/blog/tag/optimization" title="Optimization" rel="tag nofollow">Optimization</a>, <a href="http://www.safercode.com/blog/tag/optimization-techniques" title="Optimization techniques" rel="tag nofollow">Optimization techniques</a>, <a href="http://www.safercode.com/blog/tag/pipelining" title="Pipelining" rel="tag nofollow">Pipelining</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.safercode.com/blog/2008/10/28/optimizing-switch-case-statements-in-c-for-speed.html" title="Optimizing Switch-Case Statements In C For Speed (October 28, 2008)">Optimizing Switch-Case Statements In C For Speed</a> (11)</li>
	<li><a href="http://www.safercode.com/blog/2009/02/24/volatile-c-keyword-myths-dispelled.html" title="Volatile: C Keyword Myths Dispelled (February 24, 2009)">Volatile: C Keyword Myths Dispelled</a> (12)</li>
	<li><a href="http://www.safercode.com/blog/2008/10/14/and-so-it-begins.html" title="And So It Begins&#8230; (October 14, 2008)">And So It Begins&#8230;</a> (0)</li>
	<li><a href="http://www.safercode.com/blog/2009/02/04/const-keyword-explained.html" title="&quot;const&quot; Keyword Explained (February 4, 2009)">&quot;const&quot; Keyword Explained</a> (17)</li>
	<li><a href="http://www.safercode.com/blog/2008/11/11/validating-untrusted-string-inputs.html" title="Validating Untrusted String Inputs (November 11, 2008)">Validating Untrusted String Inputs</a> (1)</li>
</ul>

<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/SaferCode?a=-cwyOMimf5o:zHECs5JD17E:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SaferCode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=-cwyOMimf5o:zHECs5JD17E:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=-cwyOMimf5o:zHECs5JD17E:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=-cwyOMimf5o:zHECs5JD17E:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=-cwyOMimf5o:zHECs5JD17E:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=-cwyOMimf5o:zHECs5JD17E:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=-cwyOMimf5o:zHECs5JD17E:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=-cwyOMimf5o:zHECs5JD17E:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=-cwyOMimf5o:zHECs5JD17E:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SaferCode/~4/-cwyOMimf5o" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.safercode.com/blog/2009/01/27/tweak-your-code-for-speed-unroll-those-loops-part-1.html/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://www.safercode.com/blog/2009/01/27/tweak-your-code-for-speed-unroll-those-loops-part-1.html</feedburner:origLink></item>
	</channel>
</rss><!-- Dynamic page generated in 1.023 seconds. --><!-- Cached page generated by WP-Super-Cache on 2009-11-05 13:35:03 -->
