<?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>Tue, 05 Jan 2010 07:59:56 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/SaferCode" /><feedburner:info uri="safercode" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><image><link>http://www.safercode.com/blog/logo.png</link><url>http://www.safercode.com/blog/logo.png</url><title>Safer Code</title></image><feedburner:emailServiceId>SaferCode</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>Weird Usage Of “select” in perl</title>
		<link>http://feedproxy.google.com/~r/SaferCode/~3/rVXOBCwcUqY/perl-select-autoflush.html</link>
		<comments>http://www.safercode.com/blog/2009/12/29/perl-select-autoflush.html#comments</comments>
		<pubDate>Tue, 29 Dec 2009 00:58:18 +0000</pubDate>
		<dc:creator>Shantanu Goel</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Other Languages]]></category>
		<category><![CDATA[autoflush. STDOUT]]></category>
		<category><![CDATA[file-handle autoflush in perl]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[select]]></category>

		<guid isPermaLink="false">http://www.safercode.com/blog/2009/12/29/perl-select-autoflush.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 times while going through some perl code, you must have come across snippets like &#8220;select((select(fh), $&#124;=1)[0])&#8221; and wondered what this means, even though you might know that:

$&#124;=1 is used for setting autoflush (i.e. unbuffered data output) and that
select is used to set the default output to a given file handle instead of STDOUT

Whenever I [...]]]></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 times while going through some perl code, you must have come across snippets like &#8220;select((select(fh), $|=1)[0])&#8221; and wondered what this means, even though you might know that:</p>
<ul>
<li>$|=1 is used for setting autoflush (i.e. unbuffered data output) and that</li>
<li>select is used to set the default output to a given file handle instead of STDOUT</li>
</ul>
<p>Whenever I face any issue with a code fragment, I try to break it down into simpler terms to understand it from the beginning (like I did for my random number generation post). So, these are the steps in which I progressed:</p>
<ul>
<li>select(fh) replaces the STDOUT with fh and returns the old filehandle (i.e. STDOUT).</li>
<li>(select(fh),$|=1) does the above and then sets this new output to autoflush</li>
<li>From perl&#8217;s online docs, I found that the output of the above is a list, the first element of which is the old Filehandle</li>
<li>So, (select(fh),$|=1)[0] gives us STDOUT</li>
<li>Then select(select(fh, $|=1)[0]) basically just sets the default output back to STDOUT</li>
</ul>
<p>So, what is the use of all this. Basically, this is nothing but a trick to set autoflush for any filehandle. Now, there is a very simple way to do this. You just need to include the IO::Handle module (by writing &#8220;use IO::Handle;&#8221; in your script) and then call &#8220;fh-&gt;autoflush(1)&#8221; on your file handle (Use 0 as parameter to disable autoflushing). This is much cleaner although it means longer run times as your script now has to include and compile lot of new lines of code because the module you added.
<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/12/29/perl-select-autoflush.html">Weird Usage Of &#8220;select&#8221; in perl</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%2F12%2F29%2Fperl-select-autoflush.html&amp;title=Weird%20Usage%20Of%20%22select%22%20in%20perl&amp;bodytext=Many%20times%20while%20going%20through%20some%20perl%20code%2C%20you%20must%20have%20come%20across%20snippets%20like%20%22select%28%28select%28fh%29%2C%20%24%7C%3D1%29%5B0%5D%29%22%20and%20wondered%20what%20this%20means%2C%20even%20though%20you%20might%20know%20that%3A%0D%0A%0D%0A%09%24%7C%3D1%20is%20used%20for%20setting%20autoflush%20%28i.e.%20unbuffered%20data%20output%29" 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%2F12%2F29%2Fperl-select-autoflush.html&amp;title=Weird%20Usage%20Of%20%22select%22%20in%20perl&amp;notes=Many%20times%20while%20going%20through%20some%20perl%20code%2C%20you%20must%20have%20come%20across%20snippets%20like%20%22select%28%28select%28fh%29%2C%20%24%7C%3D1%29%5B0%5D%29%22%20and%20wondered%20what%20this%20means%2C%20even%20though%20you%20might%20know%20that%3A%0D%0A%0D%0A%09%24%7C%3D1%20is%20used%20for%20setting%20autoflush%20%28i.e.%20unbuffered%20data%20output%29" 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%2F12%2F29%2Fperl-select-autoflush.html&amp;t=Weird%20Usage%20Of%20%22select%22%20in%20perl" 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%2F12%2F29%2Fperl-select-autoflush.html&amp;title=Weird%20Usage%20Of%20%22select%22%20in%20perl" 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%2F12%2F29%2Fperl-select-autoflush.html&amp;title=Weird%20Usage%20Of%20%22select%22%20in%20perl" 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%2F12%2F29%2Fperl-select-autoflush.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/autoflush-stdout" title="autoflush. STDOUT" rel="tag nofollow">autoflush. STDOUT</a>, <a href="http://www.safercode.com/blog/tag/file-handle-autoflush-in-perl" title="file-handle autoflush in perl" rel="tag nofollow">file-handle autoflush in perl</a>, <a href="http://www.safercode.com/blog/tag/perl" title="perl" rel="tag nofollow">perl</a>, <a href="http://www.safercode.com/blog/tag/select" title="select" rel="tag nofollow">select</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li>No related posts.</li>
	</ul>

<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/SaferCode?a=rVXOBCwcUqY:Cwv79tx4YAU:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SaferCode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=rVXOBCwcUqY:Cwv79tx4YAU:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=rVXOBCwcUqY:Cwv79tx4YAU:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=rVXOBCwcUqY:Cwv79tx4YAU:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=rVXOBCwcUqY:Cwv79tx4YAU:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=rVXOBCwcUqY:Cwv79tx4YAU:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=rVXOBCwcUqY:Cwv79tx4YAU:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=rVXOBCwcUqY:Cwv79tx4YAU:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=rVXOBCwcUqY:Cwv79tx4YAU:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SaferCode/~4/rVXOBCwcUqY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.safercode.com/blog/2009/12/29/perl-select-autoflush.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.safercode.com/blog/2009/12/29/perl-select-autoflush.html</feedburner:origLink></item>
		<item>
		<title>Structure Initialization (All Elements to 0) In C</title>
		<link>http://feedproxy.google.com/~r/SaferCode/~3/GD2OeVnKXvw/structure-initialization-c.html</link>
		<comments>http://www.safercode.com/blog/2009/12/24/structure-initialization-c.html#comments</comments>
		<pubDate>Wed, 23 Dec 2009 18:56:11 +0000</pubDate>
		<dc:creator>Shantanu Goel</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[struct initialization]]></category>
		<category><![CDATA[structure initialization]]></category>

		<guid isPermaLink="false">http://www.safercode.com/blog/2009/12/24/structure-initialization-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/ -->A global or static structure is automatically initialized by all of its elements as 0 or null (In case of pointers). But if you want to initialize a local struct to this, what would you do? Many would say that would use a memset or calloc to set all the elements of that structure instance [...]]]></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>A global or static structure is automatically initialized by all of its elements as 0 or null (In case of pointers). But if you want to initialize a local struct to this, what would you do? Many would say that would use a memset or calloc to set all the elements of that structure instance to 0. But this is incorrect as a null pointer might not be same as 0. So, the correct way to do this would be like:</p>
<pre><span style=" font-family:'Courier New,courier';">struct a b = {0};</span></pre>
<p>What this does is that it initializes the first element of the structure b to 0 (or null pointer if it is a pointer) and the rest of the elements are initialized like they would have been done if the structure was global or static.</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/12/24/structure-initialization-c.html">Structure Initialization (All Elements to 0) 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%2F12%2F24%2Fstructure-initialization-c.html&amp;title=Structure%20Initialization%20%28All%20Elements%20to%200%29%20In%20C&amp;bodytext=A%20global%20or%20static%20structure%20is%20automatically%20initialized%20by%20all%20of%20its%20elements%20as%200%20or%20null%20%28In%20case%20of%20pointers%29.%20But%20if%20you%20want%20to%20initialize%20a%20local%20struct%20to%20this%2C%20what%20would%20you%20do%3F%20Many%20would%20say%20that%20would%20use%20a%20memset%20or%20calloc%20to%20set%20all%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%2F12%2F24%2Fstructure-initialization-c.html&amp;title=Structure%20Initialization%20%28All%20Elements%20to%200%29%20In%20C&amp;notes=A%20global%20or%20static%20structure%20is%20automatically%20initialized%20by%20all%20of%20its%20elements%20as%200%20or%20null%20%28In%20case%20of%20pointers%29.%20But%20if%20you%20want%20to%20initialize%20a%20local%20struct%20to%20this%2C%20what%20would%20you%20do%3F%20Many%20would%20say%20that%20would%20use%20a%20memset%20or%20calloc%20to%20set%20all%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%2F12%2F24%2Fstructure-initialization-c.html&amp;t=Structure%20Initialization%20%28All%20Elements%20to%200%29%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%2F12%2F24%2Fstructure-initialization-c.html&amp;title=Structure%20Initialization%20%28All%20Elements%20to%200%29%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%2F12%2F24%2Fstructure-initialization-c.html&amp;title=Structure%20Initialization%20%28All%20Elements%20to%200%29%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%2F12%2F24%2Fstructure-initialization-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/c" title="C" rel="tag nofollow">C</a>, <a href="http://www.safercode.com/blog/tag/struct-initialization" title="struct initialization" rel="tag nofollow">struct initialization</a>, <a href="http://www.safercode.com/blog/tag/structure-initialization" title="structure initialization" rel="tag nofollow">structure initialization</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> (14)</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=GD2OeVnKXvw:VEZi6Zy6BHc:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SaferCode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=GD2OeVnKXvw:VEZi6Zy6BHc:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=GD2OeVnKXvw:VEZi6Zy6BHc:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=GD2OeVnKXvw:VEZi6Zy6BHc:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=GD2OeVnKXvw:VEZi6Zy6BHc:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=GD2OeVnKXvw:VEZi6Zy6BHc:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=GD2OeVnKXvw:VEZi6Zy6BHc:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=GD2OeVnKXvw:VEZi6Zy6BHc:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=GD2OeVnKXvw:VEZi6Zy6BHc:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SaferCode/~4/GD2OeVnKXvw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.safercode.com/blog/2009/12/24/structure-initialization-c.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.safercode.com/blog/2009/12/24/structure-initialization-c.html</feedburner:origLink></item>
		<item>
		<title>Random Number Between Two Integers</title>
		<link>http://feedproxy.google.com/~r/SaferCode/~3/W-KnQOQ90Hg/random-number-between-two-integers.html</link>
		<comments>http://www.safercode.com/blog/2009/12/08/random-number-between-two-integers.html#comments</comments>
		<pubDate>Tue, 08 Dec 2009 13:03:13 +0000</pubDate>
		<dc:creator>Shantanu Goel</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[rand]]></category>
		<category><![CDATA[Random Numbers]]></category>
		<category><![CDATA[RAND_MAX]]></category>

		<guid isPermaLink="false">http://www.safercode.com/blog/2009/12/08/random-number-between-two-integers.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/ -->This is a topic that is quite easy and doesn’t need much explanation but still many people manage to mess it up. Not going into a hyperbole, I’ll get straight to the point. When asked, people can quickly tell you how to get a random number between 0 and b (b being any number below [...]]]></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>This is a topic that is quite easy and doesn’t need much explanation but still many people manage to mess it up. Not going into a hyperbole, I’ll get straight to the point. When asked, people can quickly tell you how to get a random number between 0 and b (b being any number below the maximum random number possible, which is defined as RAND_MAX by most C compilers). Using the function “rand” provided by most C libraries, this is as simple as:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">result <span style="color: #339933;">=</span> rand<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> b<span style="color: #339933;">;</span></pre></div></div>

<p>Basically, given any random number, if you take its modulus with a, you will obviously get a number between 0 and a -1. This is all fine and dandy, so now someone asks you to generate a random number between&#160; a and b (a &lt; b). This one is also really simple but few people fumble out still. Just think of it this way.</p>
<ol>
<li>If you add 1 to the above equation’s right hand side, your random number will be between 1 and a. So, basically your “lower limit” is raised by one. In the above case, your lower limit is a, so just raise it by a by adding it to right hand side, to arrive at this partial solution.

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">result <span style="color: #339933;">=</span> rand<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> b <span style="color: #339933;">+</span> a<span style="color: #339933;">;</span></pre></div></div>

</li>
<li>To complete the equation, now think of the gap between the minimum and maximum result obtained from original equation. Minimum is 0 and maximum is (b-1). But your desired gap is (b-a). Since taking modulus with respect to b, gives you a gap of b-1, to get the desired gap, you need to take mod with respect to ((b-a)+1). So, minimum value this will give you is 0 and maximum would be (b-a) +1 -1 = b-a. So, your final equation becomes

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">result <span style="color: #339933;">=</span> rand<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> <span style="color: #009900;">&#40;</span>b <span style="color: #339933;">-</span> a <span style="color: #339933;">+</span> <span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> a<span style="color: #339933;">;</span></pre></div></div>

</li>
</ol>
<p>This will give you a minimum value of 0 + a = a</p>
<p>and a maximum of b &#8211; a + a = b.</p>
<p>Note that the above solution includes the limits for the result. If you don’t want to include the limits (i.e. minimum result = a + 1 and maximum result = b &#8211; 1) and , then just add (a + 1) instead of a in step 1 and use (b &#8211; a -1) for your modulus operation instead of (b &#8211; a + 1) in step 2 to make the equation:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">result <span style="color: #339933;">=</span> rand<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> <span style="color: #009900;">&#40;</span>b <span style="color: #339933;">-</span> a <span style="color: #339933;">-</span> <span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> a <span style="color: #339933;">+</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span></pre></div></div>

<p>Note that in the above equation we used b &#8211; a -1, though on the surface it looks like we could have gone with just (b-a). After all we just wanted to decrease the upper limit by 1. But the reason we had to decrement by an extra place is because of the 1 we added to raise the lower limit (a +1).</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/12/08/random-number-between-two-integers.html">Random Number Between Two Integers</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%2F12%2F08%2Frandom-number-between-two-integers.html&amp;title=Random%20Number%20Between%20Two%20Integers&amp;bodytext=This%20is%20a%20topic%20that%20is%20quite%20easy%20and%20doesn%E2%80%99t%20need%20much%20explanation%20but%20still%20many%20people%20manage%20to%20mess%20it%20up.%20Not%20going%20into%20a%20hyperbole%2C%20I%E2%80%99ll%20get%20straight%20to%20the%20point.%20When%20asked%2C%20people%20can%20quickly%20tell%20you%20how%20to%20get%20a%20random%20number%20betwee" 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%2F12%2F08%2Frandom-number-between-two-integers.html&amp;title=Random%20Number%20Between%20Two%20Integers&amp;notes=This%20is%20a%20topic%20that%20is%20quite%20easy%20and%20doesn%E2%80%99t%20need%20much%20explanation%20but%20still%20many%20people%20manage%20to%20mess%20it%20up.%20Not%20going%20into%20a%20hyperbole%2C%20I%E2%80%99ll%20get%20straight%20to%20the%20point.%20When%20asked%2C%20people%20can%20quickly%20tell%20you%20how%20to%20get%20a%20random%20number%20betwee" 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%2F12%2F08%2Frandom-number-between-two-integers.html&amp;t=Random%20Number%20Between%20Two%20Integers" 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%2F12%2F08%2Frandom-number-between-two-integers.html&amp;title=Random%20Number%20Between%20Two%20Integers" 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%2F12%2F08%2Frandom-number-between-two-integers.html&amp;title=Random%20Number%20Between%20Two%20Integers" 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%2F12%2F08%2Frandom-number-between-two-integers.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/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/rand_max" title="RAND_MAX" rel="tag nofollow">RAND_MAX</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<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>
</ul>

<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/SaferCode?a=W-KnQOQ90Hg:zJLz-SyUJtM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/SaferCode?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=W-KnQOQ90Hg:zJLz-SyUJtM:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=W-KnQOQ90Hg:zJLz-SyUJtM:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=W-KnQOQ90Hg:zJLz-SyUJtM:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=W-KnQOQ90Hg:zJLz-SyUJtM:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=W-KnQOQ90Hg:zJLz-SyUJtM:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=W-KnQOQ90Hg:zJLz-SyUJtM:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=W-KnQOQ90Hg:zJLz-SyUJtM:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=W-KnQOQ90Hg:zJLz-SyUJtM:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/SaferCode/~4/W-KnQOQ90Hg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.safercode.com/blog/2009/12/08/random-number-between-two-integers.html/feed</wfw:commentRss>
		<slash:comments>14</slash:comments>
		<feedburner:origLink>http://www.safercode.com/blog/2009/12/08/random-number-between-two-integers.html</feedburner:origLink></item>
		<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> (22)</li>
</ul>

<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/SaferCode?a=pJImnPjgCJw:HfwxFhwv5Tg: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:HfwxFhwv5Tg:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=pJImnPjgCJw:HfwxFhwv5Tg:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=pJImnPjgCJw:HfwxFhwv5Tg:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=pJImnPjgCJw:HfwxFhwv5Tg:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=pJImnPjgCJw:HfwxFhwv5Tg:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=pJImnPjgCJw:HfwxFhwv5Tg:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=pJImnPjgCJw:HfwxFhwv5Tg:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=pJImnPjgCJw:HfwxFhwv5Tg: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>5</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> (22)</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> (14)</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:KKhsrHVbTm4: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:KKhsrHVbTm4:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=PIDlnndlBDo:KKhsrHVbTm4:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=PIDlnndlBDo:KKhsrHVbTm4:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=PIDlnndlBDo:KKhsrHVbTm4:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=PIDlnndlBDo:KKhsrHVbTm4:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=PIDlnndlBDo:KKhsrHVbTm4:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=PIDlnndlBDo:KKhsrHVbTm4:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=PIDlnndlBDo:KKhsrHVbTm4: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>9</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> (22)</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> (14)</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> (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/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:cFNoTS1yaFU: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:cFNoTS1yaFU:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=ralg1dUJXVM:cFNoTS1yaFU:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=ralg1dUJXVM:cFNoTS1yaFU:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=ralg1dUJXVM:cFNoTS1yaFU:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=ralg1dUJXVM:cFNoTS1yaFU:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=ralg1dUJXVM:cFNoTS1yaFU:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/SaferCode?a=ralg1dUJXVM:cFNoTS1yaFU:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/SaferCode?i=ralg1dUJXVM:cFNoTS1yaFU: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>11</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> (18)</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> (11)</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> (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>
</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>14</slash:comments>
		<feedburner:origLink>http://www.safercode.com/blog/2009/02/24/volatile-c-keyword-myths-dispelled.html</feedburner:origLink></item>
	</channel>
</rss><!-- Dynamic page generated in 0.799 seconds. --><!-- Cached page generated by WP-Super-Cache on 2010-09-07 11:04:53 -->
