<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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/"
	>

<channel>
	<title>coder . cl &#187; c++</title>
	<atom:link href="http://coder.cl/category/programming/cxx/feed/" rel="self" type="application/rss+xml" />
	<link>http://coder.cl</link>
	<description>system programmer &#38; web developer</description>
	<lastBuildDate>Thu, 29 Jul 2010 21:52:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>c++ type casting operators</title>
		<link>http://coder.cl/2010/07/c-type-casting-operators/</link>
		<comments>http://coder.cl/2010/07/c-type-casting-operators/#comments</comments>
		<pubDate>Sun, 25 Jul 2010 21:25:52 +0000</pubDate>
		<dc:creator>Daniel Molina Wegener</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=740</guid>
		<description><![CDATA[Traditionally, C programmers and Java programmers are accustomed to use the type casting form: (type)variable. C++, instead of that classical type casting form, has various type casting operators, used for different purposes. Each operator is used with different kinds of references, for example, you can not use the static_cast operator with virtual classes. Type casting [...]]]></description>
			<content:encoded><![CDATA[<p>Traditionally, <strong>C</strong> programmers and <strong>Java</strong> programmers are accustomed to use the type casting form: <i>(type)variable</i>. <strong>C++</strong>, instead of that classical type casting form, has various type casting operators, used for different purposes. Each operator is used with different kinds of references, for example, you can not use the <i>static_cast</i> operator with virtual classes. Type casting operators in <strong>C++</strong> has a syntax very similar to <i>C++ Templates</i>: <i>cast_operator&lt;type&gt;(variable)</i>.</p>
<p><span id="more-740"></span></p>
<p></p>
<h3>const_cast operators</h3>
<p>If you want an expression to being <i>const</i>, just use the <i>const_cast</i> operator. For example if a legacy function written in <i>C</i> requires of a <i>const</i> argument, just pass a non-const argument by using the <i>const_cast</i> operator:</p>
<pre name="code" class="cpp">
extern "C" {
    void my_function(const char *p);
};

std::string s = std::string("hello world");
my_function(const_cast&lt;char *&gt;(s.c_str()));
</pre>
<p></p>
<h3>static_cast operator</h3>
<p>The static_cast operator performs the conversion unconditionally, without verifying data types at <i>compile time</i>. This makes this operator quite dangerous, so, you need to verify data types before you use variables in this kind of type casting.</p>
<pre name="code" class="cpp">
if (typeid(*ptr_a) == typeid(MyClass)) {
    ptr_b = static_cast&lt;MyClass&gt;(ptr_a);
    ptr_b-&gt;applySomeMethod();
}
</pre>
<p>You can use the <i>typeid</i> C++ builtin to verify the data type. Also, you must consider that this operator is valid only if the conversion is explicit. Suppose <i>Parent</i> is a base class to <i>Child</i> and that <i>Unrelated</i> is an unrelated class. Then conversions from <i>Child</i> to <i>Parent</i> are valid, but a conversion from <i>Child</i> to <i>Unrelated</i> is disallowed:</p>
<pre name="code" class="cpp">
Parent a;
Child b;
Parent *a_1 = static_cast&lt;Parent *&gt;(&amp;b); // valid upcast
Unrelated *c_1 = static_cast&lt;Unrelated *&gt;(&amp;b_1); // invalid, Unrelated
</pre>
<p>The best usage for the <i>static_cast</i> opertaor, are numerical conversions, so you can cast from int, double, float and others of similar type to another int, double, float and similar types, including <i>enum types</i>. Some compilers does this kind of conversion explicit, but more strict compilers usually throw the proper warning on this kinds of assignment, without the proper type casting operation (line 4).</p>
<pre name="code" class="cpp">
float a;
int b;
a = static_cast&lt;float&gt;(b);
a = b;
</pre>
<p></p>
<h3>dynamic_cast operator</h3>
<p>The <i>dynamic_cast</i> operator, among other things, does a runtime check over types applied on the cast operation. As the above example of <i>static_cast</i> operator, dynamic cast does the <i>typeid()</i> checking. Then, if you have a pointer or reference to an object whose declared type is a base class, but you need to obtain a derived class pointer or reference, you should use <i>dynamic_cast</i>, since the <i>dynamic_cast</i> operator is another RTTI (<i>Run-time type information</i>) operator. The use of <i>dynamic_cast</i> derives into more overhead of your program, so you must use it with moderation.</p>
<pre name="code" class="cpp">
if (ptr_b == static_cast&lt;MyClass&gt;(ptr_a);) {
    ptr_b-&gt;applySomeMethod();
}
</pre>
<p>If the type checking and conversion fails, the operator returns a non-null reference, else it will return a null reference (zero). Also, some compilers will advice on the proper usage of the <i>dynamic_cast</i> operator, the more strict ones, will throw an error.</p>
<pre name="code" class="cpp">
Parent a;
Child b;
Parent *a_1 = dynamic_cast&lt;Parent *&gt;(&amp;b); // valid upcast
Unrelated *c_1 = dynamic_cast&lt;Unrelated *&gt;(&amp;b_1); // invalid, returns NULL
</pre>
<p></p>
<h3>reinterpret_cast operator</h3>
<p>This &mdash; possibly &mdash; is the most risky to use type casting operator. It completely transforms a pointer to very different types. For example:</p>
<pre name="code" class="cpp">
some_struct_s {
    short a;
    short b;
};
typedef struct some_struct_s some_struct_t;
some_struct_t *s;
unsigned long v = 0xd34db33f;
s = reinterpret_cast&lt;some_struct_t *&gt;(&amp;v);
std::cout &lt;&lt; s-&gt;a; // display first 2 bytes of value
</pre>
<p>As the example above, the pointer was completely transformed to different kind, with the dangerous assumption that the platform has a byte alignment that make possible to access the first to bytes of some address using this kind of operation. This cast is not portable, some compilers should throw some error about it.</p>
<p>The fact is that the <i>reinterpret_cast</i> operator overrides the initial declaration of the given variable, and makes possible to that variable to being reinterpreted as a different one. The usage of the <i>reinterpret_cast</i> must be done careful, for example for derived to base class reinterpretation.</p>
<pre name="code" class="cpp">
BaseClass a;
DerivedClass *c = reinterpret_cast&lt;DerivedClass *&gt;(&amp;a);
</pre>
<p>Since many of this kind of conversions are not possible in all compilers, you must try to setup your compiler to the most pedantic flags that it can allow. For example on GCC, you should use <i>-Wall -Wextra -Wshadow -pedantic -std=c++98</i> as compiler flags. It will keep your code portable and will allow you to create more standarized programs.</p>
<p>Here is a full compiling example of the core ideas in this post:</p>
<pre name='code' class='cpp'>

class A {
public:
	A();
	~A();
};

class B : public A {
public:
	B();
	~B();
};

A::A() {
}

A::~A() {
}

B::B() : A() {
}

B::~B() {
}

int
main(int argc, char **argv)
{

	A *ptr_a = new A();
	B *ptr_b = new B();

	A *a_1 = static_cast&lt;A *&gt;(ptr_b);
	B *b_1 = static_cast&lt;B *&gt;(ptr_a);

	A *a_2 = dynamic_cast&lt;A *&gt;(ptr_b);

	A *a_3 = reinterpret_cast&lt;A *&gt;(ptr_b);
	B *b_3 = reinterpret_cast&lt;B *&gt;(ptr_a);

	const A *a_4 = const_cast&lt;A *&gt;(ptr_a);
	const B *b_4 = const_cast&lt;B *&gt;(ptr_b);

	delete ptr_a;
	delete ptr_b;

	return 0;

}
</pre>



share this article at: 


	<a rel="nofollow"  target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fcoder.cl%2F2010%2F07%2Fc-type-casting-operators%2F&amp;title=c%2B%2B%20type%20casting%20operators&amp;source=coder+.+cl+system+programmer+%26amp%3B+web+developer&amp;summary=Traditionally%2C%20C%20programmers%20and%20Java%20programmers%20are%20accustomed%20to%20use%20the%20type%20casting%20form%3A%20%28type%29variable.%20C%2B%2B%2C%20instead%20of%20that%20classical%20type%20casting%20form%2C%20has%20various%20type%20casting%20operators%2C%20used%20for%20different%20purposes.%20Each%20operator%20is%20used%20wi" title="LinkedIn"><img src="http://coder.cl/wp-content/plugins/sociable/images/linkedin.png" title="LinkedIn" alt="LinkedIn" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fcoder.cl%2F2010%2F07%2Fc-type-casting-operators%2F&amp;title=c%2B%2B%20type%20casting%20operators&amp;notes=Traditionally%2C%20C%20programmers%20and%20Java%20programmers%20are%20accustomed%20to%20use%20the%20type%20casting%20form%3A%20%28type%29variable.%20C%2B%2B%2C%20instead%20of%20that%20classical%20type%20casting%20form%2C%20has%20various%20type%20casting%20operators%2C%20used%20for%20different%20purposes.%20Each%20operator%20is%20used%20wi" title="del.icio.us"><img src="http://coder.cl/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://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fcoder.cl%2F2010%2F07%2Fc-type-casting-operators%2F&amp;title=c%2B%2B%20type%20casting%20operators&amp;bodytext=Traditionally%2C%20C%20programmers%20and%20Java%20programmers%20are%20accustomed%20to%20use%20the%20type%20casting%20form%3A%20%28type%29variable.%20C%2B%2B%2C%20instead%20of%20that%20classical%20type%20casting%20form%2C%20has%20various%20type%20casting%20operators%2C%20used%20for%20different%20purposes.%20Each%20operator%20is%20used%20wi" title="Digg"><img src="http://coder.cl/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fcoder.cl%2F2010%2F07%2Fc-type-casting-operators%2F&amp;title=c%2B%2B%20type%20casting%20operators" title="Reddit"><img src="http://coder.cl/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fcoder.cl%2F2010%2F07%2Fc-type-casting-operators%2F&amp;t=c%2B%2B%20type%20casting%20operators" title="Facebook"><img src="http://coder.cl/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=c%2B%2B%20type%20casting%20operators%20-%20http%3A%2F%2Fcoder.cl%2F2010%2F07%2Fc-type-casting-operators%2F" title="Twitter"><img src="http://coder.cl/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fcoder.cl%2F2010%2F07%2Fc-type-casting-operators%2F&amp;title=c%2B%2B%20type%20casting%20operators&amp;annotation=Traditionally%2C%20C%20programmers%20and%20Java%20programmers%20are%20accustomed%20to%20use%20the%20type%20casting%20form%3A%20%28type%29variable.%20C%2B%2B%2C%20instead%20of%20that%20classical%20type%20casting%20form%2C%20has%20various%20type%20casting%20operators%2C%20used%20for%20different%20purposes.%20Each%20operator%20is%20used%20wi" title="Google Bookmarks"><img src="http://coder.cl/wp-content/plugins/sociable/images/googlebookmark.png" title="Google Bookmarks" alt="Google Bookmarks" class="sociable-hovers" /></a>


<br/><br/><br/><hr height="1px" width="50%" />
<div style='text-align: center !important;'><b>Copyright © 2010 Daniel Molina Wegener</b><br/><b>Atribución-No Comercial-Sin Derivadas 2.0 Chile</b><br/><a target='_new' rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/cl/"><img alt="Creative Commons License" style="border-width:0" src="/cc88x31.png" /></a></div>
<br/><hr height="1px" width="100%" />
<p><small>© Daniel Molina Wegener for <a href="http://coder.cl">coder . cl</a>, 2010. | <a href="http://coder.cl/2010/07/c-type-casting-operators/">Permalink</a> | <a href="http://coder.cl/2010/07/c-type-casting-operators/#comments">No comment</a><br/>Post tags: <br/></small></p>
]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2010/07/c-type-casting-operators/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>c++0x, deprecation of exported templates</title>
		<link>http://coder.cl/2009/10/c0x-deprecation-of-exported-templates/</link>
		<comments>http://coder.cl/2009/10/c0x-deprecation-of-exported-templates/#comments</comments>
		<pubDate>Sun, 25 Oct 2009 00:24:45 +0000</pubDate>
		<dc:creator>Daniel Molina Wegener</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=440</guid>
		<description><![CDATA[C++0x, the incoming C++ standard, is subject of continuous changes. Few months ago C++0x Concepts were removed from the working draft. Now, Template Exports will be deprecated from the future standard. What does it means?. &#34;A template defines a family of classes, functions, or concept maps, or an alias for a family of types&#34;. Who [...]]]></description>
			<content:encoded><![CDATA[<p><strong>C++0x</strong>, the incoming C++ standard, is subject of continuous changes. Few months ago <a href="http://www.devx.com/cplus/Article/42365">C++0x Concepts</a> were removed from the working draft. Now, <i>Template Exports</i> will be <i>deprecated</i> from the future standard. What does it means?. <i>&quot;A template defines a family of classes, functions, or concept maps, or an alias for a family of types&quot;</i>. Who has worked with C++ templates, knows that they are the most powerful approach to <i>abstraction</i>. Also they are pretty similar to the <i>Java Generics</i>, but different enough to hold more complex classes and methods, such as working with <i>operators</i>.</p>
<p><span id="more-440"></span></p>
<p>A <i>template</i> in C++ works like a Java Generic, but it uses different semantics. For example we can use a template to overload a previously declared operator &mdash; in Java we can not overload operators &mdash; and change its behavior. We can also define templates for functions, classes and methods. How do we play with them, it&#8217;s just a design issue. They have a similar behavior to <i>abstract methods</i>, but with more powerful semantics, allowing us to work directly with <i>named types</i>.</p>
<pre name="code" class="cpp">
/* example template function */
#include &lt;iostream&gt;
#include &lt;vector&gt;

template &lt;class T&gt;
const T&amp; smaller_v(const T&amp; a, const T&amp; b)
{
    if (a.size() &gt; b.size()) {
        return b;
    } else {
        return a;
    }
}

int main(void)
{
    // we play around with three vectors
    std::vector&lt;int&gt; a = std::vector&lt;int&gt;();
    std::vector&lt;int&gt; b = std::vector&lt;int&gt;();
    std::vector&lt;int&gt; c;
    // we put two elements in a vector
    a.push_back(1);
    a.push_back(2);
    // we put three elements in b vector
    b.push_back(3);
    b.push_back(4);
    b.push_back(5);
    // so we compare each vector size
    c = smaller_v&lt;std::vector&lt;int&gt; &gt;(a, b);
    // after we get the smaller vector
    // through our template, we output its size
    std::cout &lt;&lt; c.size() &lt;&lt; std::endl;
    return 0;
}
</pre>
<p>We have above an example of <i>template function</i>. It plays around the same namespace and linkage of <i>main()</i>, so we don&#8217;t need to <i>export</i> it. But what happens to foreign templates, where we need to <i>import them</i> into the working namespace, at the time they are declared in <i>external linkage</i>. We use the <i>export</i> keyword. How were affected the <i>template declarations</i> before they were removed from the C++0x standard?</p>
<blockquote><p>
A <i>template-declaration</i> may be preceded by the export keyword. Such a template is said to be exported. Declaring exported a class template is equivalent to declaring exported all of its non-inline member functions, static data members, member classes, member class templates, and non-inline member function templates.
</p></blockquote>
<p>Then, templates were exported if we use the <i>export</i> keyword on them, extending the <i>export</i> to its members and the template kind.</p>
<blockquote><p>
If a template is exported in one translation unit, it shall be exported in all translation units in which it appears; no diagnostic is required. A declaration of an exported template shall appear with the export keyword before any point of instantiation (14.7.4.1) of that template in that translation unit. In addition, the first declaration of an exported template containing the export keyword shall not follow the definition of that template. The export keyword shall not be used in a friend declaration.
</p></blockquote>
<p>The template shall be exported in all translation units of its linkage, regarding its declared namespace, preventing the use of any instantiation related usage of the export keyword including the implicit restriction on exporting <i>friends</i> &mdash; but explicitly exposed in the working draft. Also the standard refers to templates contained in unnamed namespaces to not be exported outside of its linkage. You may ask what is a <i>translation unit</i> in <b>C++</b>?</p>
<blockquote><p>
The text of the program is kept in units called source files in this International Standard. A source file together with all the headers (17.6.1.2) and source files included (16.2) via the preprocessing directive #include, less any source lines skipped by any of the conditional inclusion (16.1) preprocessing directives, is called a translation unit. [ Note: a <b>C++</b> program need not all be translated at the same time. &mdash; end note ]
</p></blockquote>
<h3>conclusion</h3>
<p>The explicit export of a template, by using the <i>exported templates</i> feature, is restricted on the implementation definition, so the deprecation of the <i>explicit export</i> and any implementation must regard at least the deprecated standard recommendation. So, it lefts to <i>implementation specific</i> or <i>undefined behavior</i> for exported templates in future standards, since they are thinking to remove it completely. In some way I personally feel that they are decapitating the original design of <b>C++0x</b>, which was very powerful at his original specification. Such as the removed specification for <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1758.pdf">Concepts for C++</a> and <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2780.pdf">nice formal designs.</a></p>



share this article at: 


	<a rel="nofollow"  target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fcoder.cl%2F2009%2F10%2Fc0x-deprecation-of-exported-templates%2F&amp;title=c%2B%2B0x%2C%20deprecation%20of%20exported%20templates&amp;source=coder+.+cl+system+programmer+%26amp%3B+web+developer&amp;summary=C%2B%2B0x%2C%20the%20incoming%20C%2B%2B%20standard%2C%20is%20subject%20of%20continuous%20changes.%20Few%20months%20ago%20C%2B%2B0x%20Concepts%20were%20removed%20from%20the%20working%20draft.%20Now%2C%20Template%20Exports%20will%20be%20deprecated%20from%20the%20future%20standard.%20What%20does%20it%20means%3F.%20%26quot%3BA%20template%20defines%20a%20" title="LinkedIn"><img src="http://coder.cl/wp-content/plugins/sociable/images/linkedin.png" title="LinkedIn" alt="LinkedIn" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fcoder.cl%2F2009%2F10%2Fc0x-deprecation-of-exported-templates%2F&amp;title=c%2B%2B0x%2C%20deprecation%20of%20exported%20templates&amp;notes=C%2B%2B0x%2C%20the%20incoming%20C%2B%2B%20standard%2C%20is%20subject%20of%20continuous%20changes.%20Few%20months%20ago%20C%2B%2B0x%20Concepts%20were%20removed%20from%20the%20working%20draft.%20Now%2C%20Template%20Exports%20will%20be%20deprecated%20from%20the%20future%20standard.%20What%20does%20it%20means%3F.%20%26quot%3BA%20template%20defines%20a%20" title="del.icio.us"><img src="http://coder.cl/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://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fcoder.cl%2F2009%2F10%2Fc0x-deprecation-of-exported-templates%2F&amp;title=c%2B%2B0x%2C%20deprecation%20of%20exported%20templates&amp;bodytext=C%2B%2B0x%2C%20the%20incoming%20C%2B%2B%20standard%2C%20is%20subject%20of%20continuous%20changes.%20Few%20months%20ago%20C%2B%2B0x%20Concepts%20were%20removed%20from%20the%20working%20draft.%20Now%2C%20Template%20Exports%20will%20be%20deprecated%20from%20the%20future%20standard.%20What%20does%20it%20means%3F.%20%26quot%3BA%20template%20defines%20a%20" title="Digg"><img src="http://coder.cl/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fcoder.cl%2F2009%2F10%2Fc0x-deprecation-of-exported-templates%2F&amp;title=c%2B%2B0x%2C%20deprecation%20of%20exported%20templates" title="Reddit"><img src="http://coder.cl/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fcoder.cl%2F2009%2F10%2Fc0x-deprecation-of-exported-templates%2F&amp;t=c%2B%2B0x%2C%20deprecation%20of%20exported%20templates" title="Facebook"><img src="http://coder.cl/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=c%2B%2B0x%2C%20deprecation%20of%20exported%20templates%20-%20http%3A%2F%2Fcoder.cl%2F2009%2F10%2Fc0x-deprecation-of-exported-templates%2F" title="Twitter"><img src="http://coder.cl/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fcoder.cl%2F2009%2F10%2Fc0x-deprecation-of-exported-templates%2F&amp;title=c%2B%2B0x%2C%20deprecation%20of%20exported%20templates&amp;annotation=C%2B%2B0x%2C%20the%20incoming%20C%2B%2B%20standard%2C%20is%20subject%20of%20continuous%20changes.%20Few%20months%20ago%20C%2B%2B0x%20Concepts%20were%20removed%20from%20the%20working%20draft.%20Now%2C%20Template%20Exports%20will%20be%20deprecated%20from%20the%20future%20standard.%20What%20does%20it%20means%3F.%20%26quot%3BA%20template%20defines%20a%20" title="Google Bookmarks"><img src="http://coder.cl/wp-content/plugins/sociable/images/googlebookmark.png" title="Google Bookmarks" alt="Google Bookmarks" class="sociable-hovers" /></a>


<br/><br/><br/><hr height="1px" width="50%" />
<div style='text-align: center !important;'><b>Copyright © 2009 Daniel Molina Wegener</b><br/><b>Atribución-No Comercial-Sin Derivadas 2.0 Chile</b><br/><a target='_new' rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/cl/"><img alt="Creative Commons License" style="border-width:0" src="/cc88x31.png" /></a></div>
<br/><hr height="1px" width="100%" />
<p><small>© Daniel Molina Wegener for <a href="http://coder.cl">coder . cl</a>, 2009. | <a href="http://coder.cl/2009/10/c0x-deprecation-of-exported-templates/">Permalink</a> | <a href="http://coder.cl/2009/10/c0x-deprecation-of-exported-templates/#comments">No comment</a><br/>Post tags: <br/></small></p>
]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2009/10/c0x-deprecation-of-exported-templates/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>some C++0x functional programming features</title>
		<link>http://coder.cl/2009/09/some-c0x-functional-programming-features/</link>
		<comments>http://coder.cl/2009/09/some-c0x-functional-programming-features/#comments</comments>
		<pubDate>Thu, 03 Sep 2009 01:50:53 +0000</pubDate>
		<dc:creator>Daniel Molina Wegener</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=150</guid>
		<description><![CDATA[I know a little about functional programming. Certainly, It have interesting features, such as Lambda Expressions and Closures. It seems that C++0x, the new C++ standard will support both of them. Closures, known as nested functions and Lambda Expressions, known as anonymous functions are neat tools on developing fast code with small pieces of them. [...]]]></description>
			<content:encoded><![CDATA[<p><!--:en-->
<p>I know a little about functional programming. Certainly, It have interesting features, such as <i><a href="http://en.wikipedia.org/wiki/Lambda_expression#First-class_functions" id="aj8q" title="Lambda Expressions">Lambda Expressions</a></i> and <i><a href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29" id="l2el" title="Closures">Closures</a></i>. It seems that <b><a href="http://en.wikipedia.org/wiki/C++0x" id="pc:l" title="C++0x">C++0x</a></b>, the new C++ standard will support both of them. <i>Closures</i>, known as <i>nested functions</i> and <i>Lambda Expressions</i>, known as <i>anonymous functions</i> are neat tools on developing fast code with small pieces of them. Lambda expressions can be used as arguments. They allow certain kind of abstractions, allowing the implementation of computational structures like <a href="http://en.wikipedia.org/wiki/Monad_%28functional_programming%29" id="lnvy" title="Monads">Monads</a> and <a href="http://en.wikipedia.org/wiki/Monoid" id="ose7" title="Monoids">Monoids</a>.</p>
<p><!--:--><span id="more-150"></span><!--:en--></p>
<p>Lambda expressions are seen in functional languages like <a href="http://en.wikipedia.org/wiki/Lisp" id="a56b" title="Lisp">Lisp</a>. Also multiparadigm languages, like Python and Ruby. We can review both of them from its origins, such as Lisp implementations.</p>
<h3>Closures</h3>
<p>From the Wikipedia article on <i>closures</i>:</p>
<blockquote><p>
In <a href="http://en.wikipedia.org/wiki/Computer_science" title="Computer science">computer science</a>, a <b>closure</b> is a <a href="http://en.wikipedia.org/wiki/First-class_function" title="First-class function">first-class function</a> with <a href="http://en.wikipedia.org/wiki/Free_variables_and_bound_variables" title="Free variables and bound variables">free variables</a> that are <a href="http://en.wikipedia.org/wiki/Name_binding" title="Name binding">bound</a> by the <a class="mw-redirect" href="http://en.wikipedia.org/wiki/Lexical_environment" title="Lexical environment">lexical environment</a>. Such a function is said to be &#8220;closed over&#8221; its free variables. A closure is defined within the scope of its free variables, and <a href="http://en.wikipedia.org/wiki/Variable_%28programming%29" title="Variable (programming)">the extent of those variables</a> is at least as long as the lifetime of the closure itself. The explicit use of closures are associated with <a href="http://en.wikipedia.org/wiki/Functional_programming" title="Functional programming">functional programming</a> and with languages such as <a class="mw-redirect" href="http://en.wikipedia.org/wiki/ML_programming_language" title="ML programming language">ML</a> and <a href="http://en.wikipedia.org/wiki/Lisp_%28programming_language%29" title="Lisp (programming language)">Lisp</a>. Closures are used to implement <a class="mw-redirect" href="http://en.wikipedia.org/wiki/Continuation_passing_style" title="Continuation passing style">continuation passing style</a>, and in this manner, <a href="http://en.wikipedia.org/wiki/Information_hiding" title="Information hiding">hide state</a>. Constructs such as <a href="http://en.wikipedia.org/wiki/Object_%28computer_science%29" title="Object (computer science)">objects</a> and <a class="mw-redirect" href="http://en.wikipedia.org/wiki/Control_structure" title="Control structure">control structures</a> can thus be implemented with closures.
</p></blockquote>
<p>A closure is bound to <i>nested functions</i>. The scope of a nested function allows the reuse of variables which are local to the container function. In this case, a closure has the next form &mdash; if we review from the Lisp perspective:</p>
<pre name="code" class="lisp" cols="80" rows="43">
;;; we have this file as test.l
(defun test-container (x)
&nbsp; (defun test-closure (y)
&nbsp;&nbsp;&nbsp; (format t "~10A" y))
&nbsp; (test-closure x))

(test-container "hola")
</pre>
<p></p>
<p>From the Lisp interpreter:</p>
<pre name="code" class="lisp" cols="80" rows="43">
&gt;(load "test.l")

Loading test.l
hola
Finished loading test.l
T
</pre>
<p></p>
<p>If you look at the code, you have the <i>test-closure</i> nested function, or as it&#8217;s called closure. The <b>C++0x</b> standard allows the use of closures in the code, you can define <i>nested functions</i>.</p>
<pre name="code" class="python" cols="80" rows="43">
### sample Python closure...
def test_container(x):
&nbsp;&nbsp;&nbsp; def test_closure(y):
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print y
&nbsp;&nbsp;&nbsp; test_closure(x)

test_container("hola")
</pre>
<p></p>
<p>The <b>C++0x</b> standard and the current working draft do not allow the direct declaration of nested functions or closures, but as is read in the current working draft: <i>&#8220;The type of the closure object is a class with a unique name, call it F, considered to be defined at the point where the lambda expression occurs&#8221;</i> [C++0x Working Draft, Sec. 5.1.2, P7]. Under this definition, and by using <i>lambda expressions</i>, we can define closures as follows:</p>
<pre name="code" class="cpp" cols="80" rows="43">
#include &lt;iostream&gt;
#include &lt;string&gt;

class TestClass {
public:
&nbsp;&nbsp; &nbsp;TestClass();
&nbsp;&nbsp; &nbsp;int csum(int a, int b);
};

int
TestClass::csum(int a, int b) {
&nbsp;&nbsp; &nbsp;// do you know what clos is? xD
&nbsp;&nbsp; &nbsp;auto clos = [](int x, int y) -&gt; int { int z = x * y; return y + z; };
&nbsp;&nbsp; &nbsp;return clos(a, b);
}

int
main (int argc, char **argv) {
&nbsp;&nbsp; &nbsp;TestClass *p = new TestClass();
&nbsp;&nbsp; &nbsp;std::cout &lt;&lt; p-&gt;csum(10, 13) &lt;&lt; std::endl;
&nbsp;&nbsp; &nbsp;return 0;
}
</pre>
<p></p>
<p>We have the magic keyword <i>auto</i> to define the anonymous class or anonymous closure object, then we can use the closure in our code. The closure itself is a <i>Lambda Expression</i>. So, let&#8217;s review what is a <i>Lambda Expression</i>.</p>
<p></p>
<h3>Lambda Expressions</h3>
<p>Lisp supports Lambda Expressions from its origins. A common example is the list and sequence processing statements where lambda expressions pass each element on sequences and lists to the anonymous functions. Let&#8217;s see an example.</p>
<p>The Wikipedia example on Lisp Lambda Expressions only shows an anonymous function:</p>
<pre name="code" class="lisp" cols="80" rows="43">
(lambda (x) (* x x))
</pre>
<p></p>
<p>If I run GCL or SBCL, I can do a little bit more applied example:</p>
<pre name="code" class="lisp" cols="80" rows="43">
&gt;(defvar test '("piwidi" "yopuz" "gon"))
TEST
&gt;(defvar test2 (map 'list #'(lambda (x) (concatenate 'string x " cheat chat")) test))
TEST2
&gt;test2
("piwidi cheat chat" "yopuz cheat chat" "gon cheat chat")
</pre>
<p></p>
<p>The example above uses an anonymous function to concatenate each string on the <i>test</i> list with the suffix string <i>&#8221; cheat chat&#8221;</i>, and uses the map call output to create the <i>test2</i> variable. With a behavior pretty similar to what a <i>monad</i> does, since we can use anonymous functions as variables, in example as list members:</p>
<pre name="code" class="lisp" cols="80" rows="43">
&gt;(defvar test3 #'(lambda (x) (concatenate 'string x " cheat chat")))
TEST3
&gt;test3
(LAMBDA-CLOSURE () () () (X) (CONCATENATE 'STRING X " cheat chat"))
;;; And then to use <i>test3</i> as part of a list:
&gt;(defvar test3 #'(lambda (x) (concatenate 'string x " cheat chat")))
TEST3
&gt;(defvar test4 '(("gon" test3) ("yopuz" test3) ("piwidi" test3)))
TEST4
&gt;test3
(LAMBDA-CLOSURE () () () (X) (CONCATENATE 'STRING X " cheat chat"))
&gt;test4
(("gon" TEST3) ("yopuz" TEST3) ("piwidi" TEST3))
</pre>
<p></p>
<p>Other languages are also implementing lambda expressions. Python have the lambda keyword to allow the declaration of anonymous functions and there are interesting articles on <a href="http://www.ibm.com/developerworks/library/l-prog.html" id="gy0c" title="Functional Programming under Python">Functional Programming under Python</a>. And surely you can be impressed by viewing that many languages allow the use of code as argument, directly as <a href="http://en.wikipedia.org/wiki/Functional_programming" id="cb80" title="functional paradigm">functional paradigm</a> does or indirectly as the <a href="http://en.wikipedia.org/wiki/Imperative_programming" id="si8n" title="imperative paradigm">imperative paradigm</a> does by using <a href="http://en.wikipedia.org/wiki/Callback_%28computer_science%29" id="zsv4" title="callbacks">callbacks</a>.</p>
<p>The <b>C++0x</b> will allow the use of <i>Lambda Expressions</i>. If we look at the Wikipedia examples, the next statement:</p>
<pre name="code" class="cpp" cols="80" rows="43">
[](int x, int y) -&gt; int { int z = x + y; return z + y; }
</pre>
<p></p>
<p>Is a <i>lambda expression</i>. The first part <b><i>[](int x, int y) -&gt; int {</i></b> have a semantic equivalence with <b><i>#&#8217;(lambda (x, y)</i></b>, where <b><i>x</i></b> and <b><i>y</i></b> are both arguments to the anonymous function. Since Lisp is not strict with data typing, the <b>C++0x</b> expression allows to define the return type of the anonymous function with the statement <i><b>-&gt; int</b></i>. The anonymous function body is <b><i>{ int z = x + y; return z + y; }</i></b>, that is semantically equivalent to the <b><i>let</i></b> or <b><i>progn</i></b> body of the Lisp expression.</p>
<blockquote><p>
We considered the possibility of supporting polymorphic lambda functions, whose parameter types need not be specified. Such a lambda function would implicitly be an unconstrained template, accepting any argument types; the body would be checked against the particular argument types used when the call to the lambda function is instantiated. Such functions would not create significant difficulties for the proposed translation model. A lambda expression whose parameter types were not specified would simply be translated to a function object whose function call operator is a template. Such lambda functions would, however, clash with the modular type-checking which we attempt to introduce to C++ via concepts [SD05, GSW+ 05].<br />
<i>&#8220;Lambda expressions and closures for C++&#8221;</i>
</p></blockquote>
<p>This is an interesting paragraph. Since anonymous functions are not templates, they will allow polymorphism with anonymous typing of their arguments, whereas those arguments will have typing constraints in the function implementation body and checked in run-time and driven by the use of standard <b>C++</b> templates: <i>A lambda expression whose parameter types were not specified would simply be translated to a function object whose function call operator is a template</i>. Well, this paper is a quiet old, since <a href="http://www.devx.com/cplus/Article/42365" id="qlyv" title="C++0x Concepts">C++0x Concepts</a> were recently removed from the standard by the C++0x working committee. The proposal does not refers to implementation issues, but leads to implementation strategies, like the expensive compile time performance which requires those lambda expressions and closures, since the leading strategy sets both of them become as a new local class, meaning that those classes must be instantiated to allow the use of their behavior.</p>
<p>Now, why are closure objects important to the <b>C++0x</b> Lambda Expressions:</p>
<blockquote><p>
The evaluation of a lambda-expression results in a closure object, which is an rvalue. Invoking the closure object executes the statements specified in the lambda-expression&#8217;s compound-statement. Each lambda expression has a unique type. Except as specified below, the type of the closure object is unspecified. [Note: A closure object behaves as a function object (20.7) whose function call operator, constructors, and data members are defined by the lambda-expression and its context. &mdash; end note]
</p></blockquote>
<p>Then, closure objects are the core type of lambda expressions, since <b>C++0x</b> supports function objects, and <b>C++0x</b> comes with the <i>&lt;functional&gt;</i> header, to allow you to work with function objects and their declaring types and core operators:</p>
<blockquote><p>
Function objects are objects with an operator() defined. In the places where one would expect to pass a pointer to a function to an algorithmic template (clause 25), the interface is specified to accept an object with an operator() defined. This not only makes algorithmic templates work with pointers to functions, but also enables them to work with arbitrary function objects.
</p></blockquote>
<p>The interesting declaration on the &lt;functional&gt; header for closures is the <b><i>function</i></b> class: <i>template&lt;FunctionType&gt; class function;</i>, which keeps the class undefined to allow your custom definition and type hierarchy.</p>
<p>Take a look on the current working draft of the C++0x, it comes interesting <img src='http://coder.cl/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p><!--:--></p>



share this article at: 


	<a rel="nofollow"  target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fcoder.cl%2F2009%2F09%2Fsome-c0x-functional-programming-features%2F&amp;title=some%20C%2B%2B0x%20functional%20programming%20features&amp;source=coder+.+cl+system+programmer+%26amp%3B+web+developer&amp;summary=I%20know%20a%20little%20about%20functional%20programming.%20Certainly%2C%20It%20have%20interesting%20features%2C%20such%20as%20Lambda%20Expressions%20and%20Closures.%20It%20seems%20that%20C%2B%2B0x%2C%20the%20new%20C%2B%2B%20standard%20will%20support%20both%20of%20them.%20Closures%2C%20known%20as%20nested%20functions%20and%20Lambda%20Expres" title="LinkedIn"><img src="http://coder.cl/wp-content/plugins/sociable/images/linkedin.png" title="LinkedIn" alt="LinkedIn" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fcoder.cl%2F2009%2F09%2Fsome-c0x-functional-programming-features%2F&amp;title=some%20C%2B%2B0x%20functional%20programming%20features&amp;notes=I%20know%20a%20little%20about%20functional%20programming.%20Certainly%2C%20It%20have%20interesting%20features%2C%20such%20as%20Lambda%20Expressions%20and%20Closures.%20It%20seems%20that%20C%2B%2B0x%2C%20the%20new%20C%2B%2B%20standard%20will%20support%20both%20of%20them.%20Closures%2C%20known%20as%20nested%20functions%20and%20Lambda%20Expres" title="del.icio.us"><img src="http://coder.cl/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://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fcoder.cl%2F2009%2F09%2Fsome-c0x-functional-programming-features%2F&amp;title=some%20C%2B%2B0x%20functional%20programming%20features&amp;bodytext=I%20know%20a%20little%20about%20functional%20programming.%20Certainly%2C%20It%20have%20interesting%20features%2C%20such%20as%20Lambda%20Expressions%20and%20Closures.%20It%20seems%20that%20C%2B%2B0x%2C%20the%20new%20C%2B%2B%20standard%20will%20support%20both%20of%20them.%20Closures%2C%20known%20as%20nested%20functions%20and%20Lambda%20Expres" title="Digg"><img src="http://coder.cl/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fcoder.cl%2F2009%2F09%2Fsome-c0x-functional-programming-features%2F&amp;title=some%20C%2B%2B0x%20functional%20programming%20features" title="Reddit"><img src="http://coder.cl/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fcoder.cl%2F2009%2F09%2Fsome-c0x-functional-programming-features%2F&amp;t=some%20C%2B%2B0x%20functional%20programming%20features" title="Facebook"><img src="http://coder.cl/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=some%20C%2B%2B0x%20functional%20programming%20features%20-%20http%3A%2F%2Fcoder.cl%2F2009%2F09%2Fsome-c0x-functional-programming-features%2F" title="Twitter"><img src="http://coder.cl/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fcoder.cl%2F2009%2F09%2Fsome-c0x-functional-programming-features%2F&amp;title=some%20C%2B%2B0x%20functional%20programming%20features&amp;annotation=I%20know%20a%20little%20about%20functional%20programming.%20Certainly%2C%20It%20have%20interesting%20features%2C%20such%20as%20Lambda%20Expressions%20and%20Closures.%20It%20seems%20that%20C%2B%2B0x%2C%20the%20new%20C%2B%2B%20standard%20will%20support%20both%20of%20them.%20Closures%2C%20known%20as%20nested%20functions%20and%20Lambda%20Expres" title="Google Bookmarks"><img src="http://coder.cl/wp-content/plugins/sociable/images/googlebookmark.png" title="Google Bookmarks" alt="Google Bookmarks" class="sociable-hovers" /></a>


<br/><br/><br/><hr height="1px" width="50%" />
<div style='text-align: center !important;'><b>Copyright © 2009 Daniel Molina Wegener</b><br/><b>Atribución-No Comercial-Sin Derivadas 2.0 Chile</b><br/><a target='_new' rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/cl/"><img alt="Creative Commons License" style="border-width:0" src="/cc88x31.png" /></a></div>
<br/><hr height="1px" width="100%" />
<p><small>© Daniel Molina Wegener for <a href="http://coder.cl">coder . cl</a>, 2009. | <a href="http://coder.cl/2009/09/some-c0x-functional-programming-features/">Permalink</a> | <a href="http://coder.cl/2009/09/some-c0x-functional-programming-features/#comments">No comment</a><br/>Post tags: <br/></small></p>
]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2009/09/some-c0x-functional-programming-features/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>interpreting valgrind messages</title>
		<link>http://coder.cl/2009/08/interpreting-valgrind-messages/</link>
		<comments>http://coder.cl/2009/08/interpreting-valgrind-messages/#comments</comments>
		<pubDate>Sun, 16 Aug 2009 00:20:50 +0000</pubDate>
		<dc:creator>Daniel Molina Wegener</dc:creator>
				<category><![CDATA[c]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=87</guid>
		<description><![CDATA[In other posts I&#8217;ve presented you some ways to detect memory leaks, conceptually rather than practically, but enough to understand them and solve those programming issues. Normally, valgrind messages. There are some posts about valgrind and well documented user guides, such as the guide written by Alex Ott. This article is about on how to [...]]]></description>
			<content:encoded><![CDATA[<p><!--:en-->
<p>In other posts I&#8217;ve presented you some ways to detect memory leaks, conceptually rather than practically, but enough to understand them and solve those programming issues. Normally, valgrind messages. There are some posts about valgrind and well documented user guides, such as <a href="http://xtalk.msk.su/~ott/en/writings/prog-checking/Valgrind.html">the guide</a> written by Alex Ott. This article is about on how to interpret <a href="http://www.valgrind.org/">valgrind</a> messages while you are using it as memory allocation debugger.</p>
<p><!--:--><span id="more-87"></span><!--:en--></p>
<p>First of all, I want to share a small script with the flags that I&#8217;m using with valgrind. Here is a small script which runs valgrind on the given program and creates a log with the valgrind output. You can find the explanation on the flags in the Alex&#8217;s article and the valgrind documentation.</p>
<div style="text-align: center;">
<img src="http://coder.cl/uploads/2009/08/ivm-bug1.jpg" border="0" alt="bug..." />
</div>
<pre name="code" class="bash" cols="80" rows="43">
#!/bin/bash

if test &quot;$#&quot; &quot;&lt;&quot; &quot;1&quot;; then
    echo &quot;$0: too few arguments&quot;
    exit 1
fi

VLG=`which valgrind`
VLG_LOG=`basename $PWD`
VLG_LOG=&quot;log.$VLG_LOG&quot;
VLG_OPTS=&quot;$VLG_OPTS --verbose&quot;
VLG_OPTS=&quot;$VLG_OPTS --trace-children=yes&quot;
VLG_OPTS=&quot;$VLG_OPTS --track-fds=yes&quot;
VLG_OPTS=&quot;$VLG_OPTS --run-libc-freeres=yes&quot;
VLG_OPTS=&quot;$VLG_OPTS --logfile-fd=1&quot;
VLG_OPTS=&quot;$VLG_OPTS --num-callers=100&quot;
VLG_OPTS=&quot;$VLG_OPTS --error-limit=no&quot;
VLG_OPTS=&quot;$VLG_OPTS --show-below-main=yes&quot;
VLG_OPTS=&quot;$VLG_OPTS --pointercheck=yes&quot;
VLG_OPTS=&quot;$VLG_OPTS --demangle=yes&quot;
VLG_OPTS=&quot;$VLG_OPTS --leak-check=yes&quot;

export VLG VLG_LOG VALGRIND_OPTS

if test -r &quot;$VLG_LOG&quot;; then
        echo &quot;$0: removing $VLG_LOG&quot;
        rm -f -v &quot;$VLG_LOG&quot;
fi
$VLG $VLG_OPTS $* 2&gt;&amp;1 | tee &quot;$VLG_LOG&quot;
</pre>
<p>This <a href="http://en.wikipedia.org/wiki/Shell_script">shell script</a> the call to valgrind &mdash; IMO &mdash; with the best options that some programs can have to debug them. This command line will generate a large trace on your command and as I&#8217;ve posted in a <a href="http://coder.cl/2009/07/19/foreign-system-call-simulations-on-freebsd/">previous topic</a>, valgrind replaces the <i>allocation system calls</i> with his own group of system calls, wrapping the original ones, just track those calls.</p>
<p></p>
<h3>invalid read of size <i>nnnn</i></h3>
<div style="text-align: center;">
<img src="http://coder.cl/uploads/2009/08/ivm-bug2.jpg" border="0" alt="bug..." />
</div>
<p>Your pointer arithmetics are bad. Yes, this message means that the program is accessing an invalid address by reading <i>nnnn</i> bytes from it. The code bellow &mdash; that seems to be ridiculous, but is not different that the error that you have in your code &mdash; would throw this message.</p>
<pre name="code" class="c" cols="80" rows="43">
#include &lt;stdio.h&gt;
int
main (int c, char **argv) {
    char test[] = &quot;hola mundo!&quot;;
    printf (&quot;%s\n&quot;, (char *)(test + 20));
    return 0;
}
</pre>
<p></p>
<p>The message obtained is as follows.</p>
<pre><code>
==22111== 1 errors in context 1 of 1:
==22111== Invalid read of size 1
==22111==    by 0x3010A4E0: vfprintf (in /lib/libc.so.6)
==22111==    by 0x300F6B2F: printf (in /lib/libc.so.6)
==22111==    by 0x8048571: main (test-invalid-read.c:11)
</code></pre>
<p>As you, see in the backtrace, the part where it reaches the invalid address is inside the <b>printf(3)</b> function, but the previous step is on the <i>line 11</i> of the file <i>test-invalid-read.c</i>.</p>
<p></p>
<h3>use of uninitialised value of size <i>nnnn</i></h3>
<div style="text-align: center;">
<img src="http://coder.cl/uploads/2009/08/ivm-bug3.jpg" border="0" alt="bug..." />
</div>
<p>By default, there is no automatic variable initialization for certain kinds of variables, all depends on the compiler implementation and the <a href="http://es.wikipedia.org/wiki/Lenguaje_de_programación_C#C99">C99</a> standard reveals it as undefined behavior. Since that condition, is required that you initialize all your variables to ensure code portability.</p>
<pre name="code" class="c" cols="80" rows="43">
#include &lt;string.h&gt;
#include &lt;stdio.h&gt;

int
main (int c, char **argv) {
    char *tst;
    printf (&quot;%s\n&quot;, tst);
    return 0;
}
</pre>
<p>The code above will produce the next error messages on valgrind.</p>
<pre><code>
==22309== 1 errors in context 1 of 6:
==22309== Use of uninitialised value of size 4
==22309==    at 0x30039DC0: memcpy (in /usr/local/lib/valgrind/vgpreload_memcheck.so)
==22309==    by 0x3010A4E0: vfprintf (in /lib/libc.so.6)
==22309==    by 0x300F6B2F: printf (in /lib/libc.so.6)
==22309==    by 0x804854B: main (test-invalid-read.c:8)
==22309==
==22309== 1 errors in context 2 of 6:
==22309== Conditional jump or move depends on uninitialised value(s)
==22309==    at 0x30039DAF: memcpy (in /usr/local/lib/valgrind/vgpreload_memcheck.so)
==22309==    by 0x3010A4E0: vfprintf (in /lib/libc.so.6)
==22309==    by 0x300F6B2F: printf (in /lib/libc.so.6)
==22309==    by 0x804854B: main (test-invalid-read.c:8)
</code></pre>
<p>Both errors are pointing to the same programming error. The variable <i>tst</i> was not initialized, and then you operate &mdash; and what makes one of the most ugliest errors on programming &mdash; using it as address reference. Also, by default <i>gcc</i> has automatic initialization of those pointers to <b>null</b>, and then you get <a href="http://qconlondon.com/london-2009/presentation/Null+References:+The+Billion+Dollar+Mistake"><i>&quot;Null References: The Billion Dollar Mistake&quot;</i></a> pointed by <a href="http://en.wikipedia.org/wiki/Tony_Hoare">Tony Hoare</a>. Remember that variable initialization is an undefined behavior according to the current C standard. Reference verification and initialization is an important task, recently was <a href="http://bertrandmeyer.com/tag/void-safety/">announced</a> a new version of <a href="http://en.wikipedia.org/wiki/Eiffel_(programming_language)">Eiffel</a> &mdash; a pure object oriented paradigm based language &mdash; that is <a href="http://docs.eiffel.com/sites/default/files/void-safe-eiffel.pdf">avoiding null deferencing</a>.</p>
<p></p>
<h3>process terminating with default action of signal <i>nn</i> (<i>SIGNAME</i>): dumping core</h3>
<div style="text-align: center;">
<img src="http://coder.cl/uploads/2009/08/ivm-bug4.jpg" border="0" alt="bug..." />
</div>
<p>Here the valgrind execution stops. Why? the program receives a <a href="http://en.wikipedia.org/wiki/Signal_(computing)">signal</a> and is terminated by the operating system. Take a look on the <b>signal(3)</b> manual page for more details.</p>
<p>The operating system generates a <a href="http://en.wikipedia.org/wiki/Core_file">core file</a>, from where you can get the proper information about the crashing instruction. All depends on the signal that the program was catching, a <tt>SIGBUS</tt> or <i>bus error</i>, means that you are writing bytes to wrong address. The code bellow shows that <i>bug</i>.</p>
<pre name="code" class="c" cols="80" rows="43">
#include &lt;string.h&gt;
#include &lt;stdio.h&gt;

int
main (int c, char **argv) {
    char tst[10];
    const char hl[] = &quot;hola mundo!&quot;;
    memset (tst, 0, sizeof(tst));
    memcpy (tst, hl, strlen(hl) + 1);
    return 0;
}
</pre>
<p>The <b>memset(3)</b> instruction sets the memory buffer pointed by <i>tst</i> to zero and it is OK. The size of <i>tst</i> is known, and since the operator <i>sizeof</i> is a compile time operator, there is no problem. If tst is a pointer instead of an array of bytes &mdash; I mean <i>&quot;char *tst&quot;</i> declaration &mdash; we can&#8217;t use <i>sizeof</i> and using it is like to get <i>sizeof(NULL)</i> &mdash; have noticed that every pointer has the same size?. If we <a href="http://www.gnu.org/software/gdb/documentation/">extract the backtrace from the core file</a>, we can reach the line of code which have the error. Depending on the signal, we can reach different kinds of errors, you must read your system documentation to know to what specific error refers it.</p>
<p></p>
<h3>other valgrind errors</h3>
<div style="text-align: center;">
<img src="http://coder.cl/uploads/2009/08/ivm-bug5.jpg" border="0" alt="bug..." />
</div>
<p>Depending on your operating system implementation, other errors can occur, if there is no proper memory protection. For example, you can have a <i>conditional jump</i> error and then an <i>invalid write</i> error. If you mix both of them and the system is not capable to protect itself of those errors, valgrind will report them. In other case, the proper <i>signal</i> will be thrown to your process and possibly a core file will be generated, then you must use the traditional debugging techniques to reach the <a href="http://en.wikipedia.org/wiki/Software_bug">bug</a>.</p>
<p></p>
<h3>conclusion</h3>
<p>You must consider learning <a href="http://en.wikipedia.org/wiki/Assembly_language">assembly language</a> and <a href="http://en.wikipedia.org/wiki/Computer_architecture">computer architecture</a> if you want to work at this level. Nowdays, by <i>C programming</i> most people understand a <i>low level</i> programming. By the years that I was studying, <i>C programming</i> was just another <i>high level language</i>, and I got the basics of programming on it, but just before I was introduced to it by reading some books &mdash; about 5 to 7 books on <i>C programming</i> &mdash; I was capable to build stronger programs.</p>
<p>Everything is important on <i>C programming</i>, from the basic techniques to complex data structures and algorithms. Most operating systems and user interfaces are made with <b>C</b> as the main programming language and also with <b>C++</b>. The applications of this language are not only applied to low level tasks. There are many programs implementing their algorithms in C and assembler to reach optimal performance, just look at <a href="http://math-atlas.sourceforge.net/">ATLAS</a>, <a href="http://www.netlib.org/blas/">BLAS</a> and some other interesting projects.</p>
<p><!--:--></p>



share this article at: 


	<a rel="nofollow"  target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fcoder.cl%2F2009%2F08%2Finterpreting-valgrind-messages%2F&amp;title=interpreting%20valgrind%20messages&amp;source=coder+.+cl+system+programmer+%26amp%3B+web+developer&amp;summary=In%20other%20posts%20I%27ve%20presented%20you%20some%20ways%20to%20detect%20memory%20leaks%2C%20conceptually%20rather%20than%20practically%2C%20but%20enough%20to%20understand%20them%20and%20solve%20those%20programming%20issues.%20Normally%2C%20valgrind%20messages.%20There%20are%20some%20posts%20about%20valgrind%20and%20well%20docu" title="LinkedIn"><img src="http://coder.cl/wp-content/plugins/sociable/images/linkedin.png" title="LinkedIn" alt="LinkedIn" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fcoder.cl%2F2009%2F08%2Finterpreting-valgrind-messages%2F&amp;title=interpreting%20valgrind%20messages&amp;notes=In%20other%20posts%20I%27ve%20presented%20you%20some%20ways%20to%20detect%20memory%20leaks%2C%20conceptually%20rather%20than%20practically%2C%20but%20enough%20to%20understand%20them%20and%20solve%20those%20programming%20issues.%20Normally%2C%20valgrind%20messages.%20There%20are%20some%20posts%20about%20valgrind%20and%20well%20docu" title="del.icio.us"><img src="http://coder.cl/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://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fcoder.cl%2F2009%2F08%2Finterpreting-valgrind-messages%2F&amp;title=interpreting%20valgrind%20messages&amp;bodytext=In%20other%20posts%20I%27ve%20presented%20you%20some%20ways%20to%20detect%20memory%20leaks%2C%20conceptually%20rather%20than%20practically%2C%20but%20enough%20to%20understand%20them%20and%20solve%20those%20programming%20issues.%20Normally%2C%20valgrind%20messages.%20There%20are%20some%20posts%20about%20valgrind%20and%20well%20docu" title="Digg"><img src="http://coder.cl/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fcoder.cl%2F2009%2F08%2Finterpreting-valgrind-messages%2F&amp;title=interpreting%20valgrind%20messages" title="Reddit"><img src="http://coder.cl/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fcoder.cl%2F2009%2F08%2Finterpreting-valgrind-messages%2F&amp;t=interpreting%20valgrind%20messages" title="Facebook"><img src="http://coder.cl/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=interpreting%20valgrind%20messages%20-%20http%3A%2F%2Fcoder.cl%2F2009%2F08%2Finterpreting-valgrind-messages%2F" title="Twitter"><img src="http://coder.cl/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fcoder.cl%2F2009%2F08%2Finterpreting-valgrind-messages%2F&amp;title=interpreting%20valgrind%20messages&amp;annotation=In%20other%20posts%20I%27ve%20presented%20you%20some%20ways%20to%20detect%20memory%20leaks%2C%20conceptually%20rather%20than%20practically%2C%20but%20enough%20to%20understand%20them%20and%20solve%20those%20programming%20issues.%20Normally%2C%20valgrind%20messages.%20There%20are%20some%20posts%20about%20valgrind%20and%20well%20docu" title="Google Bookmarks"><img src="http://coder.cl/wp-content/plugins/sociable/images/googlebookmark.png" title="Google Bookmarks" alt="Google Bookmarks" class="sociable-hovers" /></a>


<br/><br/><br/><hr height="1px" width="50%" />
<div style='text-align: center !important;'><b>Copyright © 2009 Daniel Molina Wegener</b><br/><b>Atribución-No Comercial-Sin Derivadas 2.0 Chile</b><br/><a target='_new' rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/cl/"><img alt="Creative Commons License" style="border-width:0" src="/cc88x31.png" /></a></div>
<br/><hr height="1px" width="100%" />
<p><small>© Daniel Molina Wegener for <a href="http://coder.cl">coder . cl</a>, 2009. | <a href="http://coder.cl/2009/08/interpreting-valgrind-messages/">Permalink</a> | <a href="http://coder.cl/2009/08/interpreting-valgrind-messages/#comments">No comment</a><br/>Post tags: <br/></small></p>
]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2009/08/interpreting-valgrind-messages/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
