<?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>web developer &#38; system programmer</description>
	<lastBuildDate>Tue, 15 May 2012 10:46:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>mozilla extensions with xpcom</title>
		<link>http://coder.cl/2010/07/mozilla-extensions-with-xpcom/</link>
		<comments>http://coder.cl/2010/07/mozilla-extensions-with-xpcom/#comments</comments>
		<pubDate>Sun, 01 Aug 2010 00:02:26 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[c]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=750</guid>
		<description><![CDATA[The XPCOM API can allow you to create low level extensions &#8212; I mean written in C++, with support for C and assembler through C++ &#8212; and plug ins for Mozilla products. For example, you can create an extension to browse IMAP folders from Mozilla Firefox. This API is analogous to the COM+ API on [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href='https://developer.mozilla.org/en/XPCOM'><strong>XPCOM</strong></a> API can allow you to create low level extensions &mdash; I mean written in C++, with support for C and assembler through C++ &mdash; and plug ins for <a href='http://www.mozilla.org/'>Mozilla</a> products. For example, you can create an extension to browse IMAP folders from <i>Mozilla Firefox</i>. This API is analogous to the <strong>COM+</strong> API on Micro$oft Windows. One of my most recent projects, is a <a href='http://www.mozilla.com/en-US/firefox/firefox.html'>Firefox</a> extension to handle <a href='http://en.wikipedia.org/wiki/Simple_Network_Management_Protocol'>SNMP</a> protocol requests from JavaScript, so my extension is applied from the JavaScript within the HTML in the browser, allowing Firefox to act as an SNMP client. The extension is working fine, without memory leaks and allows you to do <i>get</i> and <i>walk</i> request. Possibly it will be expanded to more requests on the future.</p>
<p><span id="more-750"></span></p>
<p></p>
<h3>interface definition</h3>
<p>JavaScript requires <i>class definitions</i> to work. So, you need to create <a href='http://en.wikipedia.org/wiki/Interface_description_language'>IDL</a> definitions of your <i>scriptable</i> classes. The syntax for the <i>XPIDL</i> is quite standard, so isn&#8217;t difficult to create interfaces with this IDL variant. To allow you to use IDL defined interfaces on JavaScript, interfaces must be defined as <i>scriptable</i> and must be derived from <i>nsISupports</i> interface, with an unique <i>uuid</i>. Let me show you an example:</p>
<pre class='brush: java;'>
#include &quot;nsISupports.idl&quot;
#include &quot;nsIMyProtocolRequest.idl&quot;
#include &quot;nsIMyProtocolResponse.idl&quot;
#include &quot;nsIMyProtocolError.idl&quot;
#include &quot;nsIMyProtocolStatus.idl&quot;
#include &quot;nsIMyProtocolService.idl&quot;

[scriptable, uuid(3455c51a-3323-4343-844f-2342526113c2)]
interface nsIMyProtocolService : nsISupports
{
    readonly attribute nsIMyProtocolError error;
    nsIMyProtocolResponse get(in nsIMyProtocolRequest req);
    nsIMyProtocolStatus getStatus(in nsIMyProtocolRequest req);
};
</pre>
<p>This will create a XPCOM object wrapped in JavaScript similar to the following example:</p>
<pre class='brush: javascript;'>
var nsIMyProtocolService = {
    error: new nsIMyProtocolError(),
    get: function (req) {
    },
    getStatus: function (req) {
    },
};
</pre>
<p><br/></p>
<h3>class definition</h3>
<p>Here, <tt>error</tt> is a read only attribute, and <tt>get()</tt> and <tt>getStatus()</tt> are methods. But this isn&#8217;t enough, that is just the <i>interface definition</i>. The implementation must be done in C++ so the interface defintion is transformed to <strong>C++</strong> code &mdash; a C++ header specifically &mdash; which must be included in the class implementation <strong>C++</strong> code file. Where need to consider a special note on class attributes and methods: Every method implementation has the form: <i>nsresult MethodName(&#8230;input parameters if any&#8230;, &#8230;output parameters if any&#8230;)</i>, where nsresult is the type of the returned status to the XPCOM API to let it know <i>how was executed</i> the method, so you can return <tt>NS_OK</tt> on execution correctness, <tt>NS_ERROR_NULL_POINTER</tt> for invalid input as null pointers, <tt>NS_ERROR_INVALID_POINTER</tt> for invalid variable input and so on. Well, the class definition inside the implementation file, should look as follow:</p>
<pre class='brush: cpp;'>
class nsMyProtocolService : public nsIMyProtocolService
{
public:
    nsMyProtocolService();
    ~nsMyProtocolService();

    nsresult GetError(nsIMyProtocolError **out);
    nsresult Get(nsIMyProtocolRequest *req,
                 nsIMyProtocolResponse **out);
    nsresult GetStatus(nsIMyProtocolRequest *req,
                 nsIMyProtocolStatus **out);
private:
    int statusCode;
    int errorCode;
    char *errorString;
    nsIMyProtocolError *currentError;
}
</pre>
<p><br/></p>
<h3>class implementation</h3>
<p>You must be a <a href='http://c2.com/cgi-bin/wiki?ThreeStarProgrammer'>two star programmer</a> to know how to implement the argument passing and method output, but I know that you are a good C and C++ programmer, so this is not an obstacle and you can act as a <i>three star programmer</i> without problems. So, the implementation, for example for the <tt>GetError()</tt> method, which has been mapped to the <i>error</i> attribute on the <i>nsIMyProtocolService</i> interface, should look as follows:</p>
<pre class='brush: cpp;'>
nsresult
nsMyProtocolService::GetError(nsIMyProtocolError **out)
{
    nsMyProtocolError *rout;
    result = NS_ERROR_NULL_POINTER;
    if (out == NULL || out == nsnull) {
        return result;
    }
    rout = new nsMyProtocolError();
    if (rout == NULL) {
        result = NS_ERROR_NOT_INITIALIZED;
        return result;
    }
    if (currentError != NULL &amp;&amp; currentError != nsnull) {
        NS_RELEASE(currentError);
        delete currentError;
    }
    rout->SetErrorCode(errorCode);
    rout->SetErrorString(errorString);
    NS_ADDREF(rout);
    *out = rout;
    result = NS_OK;
    return result;
}
</pre>
<p>On the example above, we have created a new pointer to the <i>nsIMyProtocolError</i> interface implementation. That pointer, before is being returned to the JavaScript and wrapped by the XPCOM API, must have an increased <i>reference count</i>, so Firefox do not remove that object. But as any language which uses <i>reference counting</i> in its garbage collection tasks, requires a reference counting decrement before the object is released. So you need to release those references using the <tt>NS_RELEASE</tt> macro. As any software development &mdash; with or without a garbage collector behind &mdash; you must be careful with the memory usage. Any object with a reference count different from zero, will hang Firefox, so you need to release reference counting on destructors too.</p>
<pre class='brush: cpp;'>
nsMyProtocolService::~nsMyProtocolService()
{
    if (currentError != NULL &amp;&amp; currentError != nsnull) {
        NS_RELEASE(currentError);
        delete currentError;
    }
}
</pre>
<p><br/></p>
<h3></h3>
<p>The example above shows how the destructor releases the reference counting for the <i>currentError</i> object. But think a little. Every time you call <tt>GetError()</tt>, in other words, you request the <i>error</i> attribute on the <i>nsIMyProtocolService</i> instance, you are increasing references which are left without being decreased. You need an storage for those pointers, so you can use any collection class that you want and is supported by your platform, but is recommended that you use the kind of storage classes which are present on the XPCOM API. How to create a collection?</p>
<pre class='brush: cpp;'>

nsCOMPtr&lt;nsIMutableArray&gt; container;
container = do_CreateInstance(NS_ARRAY_CONTRACTID);
</pre>
<p>The <i>nsIMutableArray</i> provides an array class which can be used inside your Firefox extension and also it can be exposed as a JavaScript array, it is an <i>scriptable</i> class, and also provides methods for pushing and extracting elements as the JavaScript array does, so you can use methods such as <tt>GetLength()</tt>, which is mapped to the <i>length</i> attribute, <tt>AppendElement()</tt>, which is mapped to the <i>append()</i> method, <tt>QueryElementAt()</tt> which is mapped to the <i>array[index]</i> operator. The <i>do_CreateInstance</i> template will allow you create instances of you interfaces, when you are requesting them from other extensions. For example if you want to use the <i>WebDAV</i> extension from your C++ extension, you need to use <i>do_CreateInstance</i> template.</p>
<p><br/></p>
<h3>component declaration</h3>
<p>Finally, you need to register and expose your components to the JavaScript interface and the XPCOM API, so you need to define a contract identifier and add some static code to you extension.</p>
<pre class='brush: cpp;'>
#define NS_MYSVC_CONTRACTID         &quot;@mozilla.org/myprotocol/service;1&quot;
#define NS_MYSVC_CID
    { /* 3455c51a-3323-4343-844f-2342526113c2 */
        0x3455c51a,
            0x3323,
            0x4343,
            { 0x84, 0x4f, 0x23, 0x42, 0x52, 0x61, 0x13, 0xc2 }
    }

NS_GENERIC_FACTORY_CONSTRUCTOR(nsMyProtocolService)
NS_DECL_CLASSINFO(nsMyProtocolService)
static const nsModuleComponentInfo components[] =
{
    { &quot;My Protocol Service&quot;, NS_MYSVC_CONTRACTID, NS_MYSVC_CID,
      nsMyProtocolServiceConstructor,
      NULL, NULL, NULL,
      NS_CI_INTERFACE_GETTER_NAME(nsMyProtocolService),
      NULL,
      &amp;NS_CLASSINFO_NAME(nsMyProtocolService)
    }
};

NS_IMPL_NSGETMODULE(nsJxSNMPService, components)
</pre>
<p>This can be used as template, where the <i>components</i> array contains the interface definitions and interface implementation references that allow you to use those classes from JavaScript. This code will:</p>
<dl>
<dt><tt>NS_GENERIC_FACTORY_CONSTRUCTOR</tt></dt>
<dd>Will declare <tt>nsMyProtocolServiceConstructor</tt> to be used as default constructor by the <i>do_CreateInstance()</i> template.</dd>
<dt><tt>NS_DECL_CLASSINFO</tt></dt>
<dd>Will declare class information referencing the <i>nsMyProtocolService</i> class to allow you to use that class information from JavaScript to be exposed to the XPCOM API.</dd>
<dt><tt>NS_MYSVC_CONTRACTID</tt></dt>
<dd>Contract (interface) identifier, it will be required by your JavaScript to instantiate you class, using the interface as was defined in <i>nsIMyProtocolService</i>.</dd>
<dt><tt>NS_MYSVC_CID</tt></dt>
<dd>This is the unique <i>uuid</i> identifier for your component. Remember that those components are quite analogous to the COM+ components on the Window$ platform.</dd>
<dt><tt>NS_IMPL_NSGETMODULE(nsJxSNMPService, components)</tt></dt>
<dd>This line finally will expose &mdash; through static code &mdash; your component to the XPCOM API, and will allow your class to being used from JavaScript or your Firefox extension. Remember that <i>components</i> is an array which can hold multiple interface and class definitions.</dd>
</dl>
<p><br/></p>
<h3>component exposition</h3>
<p>If you followed the article with a conscious reading, the following lines of JavaScript will bring you the proper guide to instantiate your own component. I&#8217;m assuming that you are an experienced <i>system programmer</i> and <i>web developer</i> to handle this article:</p>
<pre class='brush: javascript;'>
const C = Components;
const CI = C.interfaces;
const CL = C.classes;

function getContract(contract) {
  try {
    return C.classes[contract];
  } catch (e) {
    alert(e.message);
  }
}

function getService(contract, iface) {
  try {
    return getContract(contract).getService(CI[iface]);
  } catch (e) {
    alert(e.message);
  }
}

function getInterface(contract, iface) {
  try {
    return getContract(contract).createInstance(CI[iface]);
  } catch (e) {
    alert(e.message);
  }
}

try {
    var myService = getService(&quot;@mozilla.org/myprotocol/service;1&quot;,
                               &quot;nsIMyProtocolService&quot;);

    var myRequest = getService(&quot;@mozilla.org/myprotocol/request;1&quot;,
                               &quot;nsIMyProtocolRequest&quot;);

    myRequest.first_argument = 200;
    myRequest.second_argument = &quot;hello world!&quot;;
    var myResponse = myService.get(myRequest);
    if (typeof(myService.error) == &quot;object&quot;
        &amp;&amp; myService.error.status != 0) {
        alert(myService.error.toString());
    }
} catch (e) {
    alert(e.message);
}
</pre>
<p><br/></p>
<h3>interesting code to look</h3>
<p>You can start downloading the Firefox source code and take a look on the following interfaces:</p>
<ul>
<li><strong>extensions/webdav</strong>, this defines the &quot;@mozilla.org/webdav/service;1&quot; interface, allowing you to create WebDAV clients from JavaScript.</li>
<li><strong>extensions/webservices</strong>, this defines the &quot;@mozilla.org/xmlextras/proxy/webserviceproxy;1,&quot; and similar interfaces, allowing you to create WebService client proxies from JavaScript.</li>
<li><strong>extensions/sql</strong>, this folder stores &quot;@mozilla.org/sql/connection;1&quot; and similar interfaces, so Firefox can be used directly as client to query some RDBMS engines &mdash; such as PostgreSQL and SQLite.</li>
</ul>
<p>You can go on deeper reading code and references to enhance your <strong>XPCOM</strong> component development ;)</p>
<p><br/></p>
<h3>references</h3>
<ul>
<li><a href='http://en.wikipedia.org/wiki/XPCOM'><i>&quot;XPCOM&quot;</i></a>, Wikipedia Article, as introductory reading.</li>
<li><a href='http://www.ibm.com/developerworks/webservices/library/co-xpcom.html'><i>&quot;XPCOM Part 1: An introduction to XPCOM&quot;</i></a>, IBM DeveloperWorks article, by <a href='http://www.ibm.com/developerworks/webservices/library/co-xpcom.html#author1'>Rick Parrish</a>.</li>
<li><a href='http://www.ibm.com/developerworks/webservices/library/co-xpcom2.html'><i>&quot;XPCOM Part 2: XPCOM component basics&quot;</i></a>, IBM DeveloperWorks article, by <a href='http://www.ibm.com/developerworks/webservices/library/co-xpcom.html#author1'>Rick Parrish</a>.</li>
<li><a href='http://www.ibm.com/developerworks/webservices/library/co-xpcom3.html'><i>&quot;XPCOM Part 3: Setting up XPCOM&quot;</i></a>, IBM DeveloperWorks article, by <a href='http://www.ibm.com/developerworks/webservices/library/co-xpcom.html#author1'>Rick Parrish</a>.</li>
<li><a href='https://developer.mozilla.org/en/XPCOM'><i>&quot;XPCOM&quot;</i></a>, Mozilla Reference Documentation.</li>
</ul>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2010. |
<a href="http://coder.cl/2010/07/mozilla-extensions-with-xpcom/">Permalink</a> |
<a href="http://coder.cl/2010/07/mozilla-extensions-with-xpcom/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2010/07/mozilla-extensions-with-xpcom/&title=mozilla extensions with xpcom">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2010/07/mozilla-extensions-with-xpcom/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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>dmw</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 class="brush: 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 class="brush: 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 class="brush: 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 class="brush: 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 class="brush: 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 class="brush: 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 class="brush: 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 class="brush: 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 class='brush: 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>
<hr />
<p><small>© dmw 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> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2010/07/c-type-casting-operators/&title=c++ type casting operators">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</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>dmw</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 class="brush: 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>
<hr />
<p><small>© dmw 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> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2009/10/c0x-deprecation-of-exported-templates/&title=c++0x, deprecation of exported templates">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</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>dmw</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/Anonymous_function" 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 class="brush: 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 class="brush: 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 class="brush: 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 class="brush: 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 class="brush: 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 class="brush: 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 class="brush: 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 class="brush: 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 ;)</p>
<p><!--:--></p>
<hr />
<p><small>© dmw 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> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2009/09/some-c0x-functional-programming-features/&title=some C++0x functional programming features">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</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>dmw</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 class="figure">
<img src="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2009/08/ivm-bug1.jpg" border="0" alt="bug..." />
</div>
<pre class="brush: 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/foreign-system-call-emulations-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 class="figure">
<img src="http://coder.cl.qfl.wpcdn.arcostream.com/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;%sn&quot;, (char *)(test + 20));
    return 0;
}
</pre>
<p></p>
<p>The message obtained is as follows.</p>
<pre>
==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)
</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 class="figure">
<img src="http://coder.cl.qfl.wpcdn.arcostream.com/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;%sn&quot;, tst);
    return 0;
}
</pre>
<p>The code above will produce the next error messages on valgrind.</p>
<pre>
==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)
</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 class="figure">
<img src="http://coder.cl.qfl.wpcdn.arcostream.com/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 class="figure">
<img src="http://coder.cl.qfl.wpcdn.arcostream.com/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>
<hr />
<p><small>© dmw 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> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2009/08/interpreting-valgrind-messages/&title=interpreting valgrind messages">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</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>
<!-- This Quick Cache file was built for ( 2e96b290f6c5ccd2bc6830557c0aba6e coder.cl/category/programming/cxx/feed/ ) in 0.44517 seconds, on May 18th, 2012 at 11:58 am UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on May 25th, 2012 at 11:58 am UTC -->
