<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[// nandaa]]></title><description><![CDATA[I'm a software craftsman, currently heavily involved in opensource container and cloud-native platform systems. In my spare time I teach kids programming and ch]]></description><link>https://nandaa.fyi</link><generator>RSS for Node</generator><lastBuildDate>Sat, 26 Sep 2026 03:12:04 GMT</lastBuildDate><atom:link href="https://nandaa.fyi/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Software Career Longevity]]></title><description><![CDATA[At some point, I will give my proper take but for now, I would like to post an excerpt from an ACM Queue I read way back in 2011. I've been looking for it, but thank God for archive.org, found it. This was written by Michi Henning, most likely in 200...]]></description><link>https://nandaa.fyi/software-career-longevity</link><guid isPermaLink="true">https://nandaa.fyi/software-career-longevity</guid><category><![CDATA[software craftsmanship]]></category><category><![CDATA[software-career]]></category><dc:creator><![CDATA[Anthony Nandaa]]></dc:creator><pubDate>Tue, 02 Jan 2024 06:36:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/zEqkUMiMxMI/upload/e3224c4406a7def375ee197626e2af70.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>At some point, I will give my proper take but for now, I would like to post an excerpt from an ACM Queue I read way back in 2011. I've been looking for it, but thank God for archive.org, <a target="_blank" href="https://web.archive.org/web/20120927025629/http://prof.deveint.com/2011/10/career-path/">found it</a>. This was written by <a target="_blank" href="http://www.triodia.com/"><mark>Michi Henning</mark></a>, most likely in 2007.</p>
<blockquote>
<p>I am 47, and I write code. Looking around me, I realize how unusual this is: in my company, all of my programming colleagues are younger than I and, when I look at former programming colleagues, most of them no longer write code; i<mark>nstead, they have moved on to different positions (such as project manager) or have left the industry entirely. I see this trend everywhere in the software industry: older programmers are rare, quite often because no career path exists for them beyond a certain point.</mark> I recall how much effort it took me to resist a forced “promotion” into a management position at a former company — I ended up staying a programmer, but was told that f<mark>uture pay increases were pretty much out of the question if I was unwilling to move into management</mark>.</p>
<p><mark>There is also a belief that older programmers “lose the edge” and don’t cut it anymore.</mark> That belief is mistaken, in my opinion: older programmers may not burn as much midnight oil as younger ones, but that’s not because they are old, but because they get the job done without having to stay up past midnight.</p>
<p>This loss of older programmers is unfortunate, particularly when it comes to API design. While good API design can be learned, there is no substitute for experience. Many good APIs were created by programmers who had to suffer under a bad one and then decided to redo the job, but properly this time. It takes time and a healthy dose of “once burned, twice shy” to gather the expertise that is necessary to do better. Unfortunately, the industry trend is to promote precisely its most experienced people away from programming, just when they could put their accumulated expertise to good use.</p>
<p>Another trend is for companies to promote their best programmers to designer or system architect. Typically, these programmers are farmed out to various projects as consultants, with the aim of ensuring that the project takes off on the right track and avoids mistakes it might make without the wisdom of the consultants. The intent of this practice is laudable, but the outcome is usually sobering: because the consultants are so valuable, having given their advice, they are moved to the next project long before implementation is finished, let alone testing and delivery. By the time the consultants have moved on, any problems with their earlier sage advice are no longer their problems, but the problems of a project they have long since left behind. In other words, the consultants never get to live through the consequences of their own design decisions, which is a perfect way to breed them into incompetence. The way to keep designers sharp and honest is to make them eat their own dog food. Any process that deprives designers of that feedback is ultimately doomed to failure.</p>
</blockquote>
<p>For myself, I've chosen to stay on the software engineering IC (individual contributor) path as long as God would have me. Age is slowly catching up with me but that has nothing to do with how I still enjoy software craftmanship.</p>
<p>Luckily, there are so many examples of people around to look up to. Where I currently work, we have people who have been writing code for more than 25, 30 years; and they are still going, still on the IC track. I don't think that's an exclusive club, it's a club for the willing -- sign me up! :)</p>
]]></content:encoded></item><item><title><![CDATA[Technical Books for 2024 (and 2025)]]></title><description><![CDATA[I strongly advocate for learning in the public due to several compelling reasons:

One or two people can learn from you.

Builds up the culture of life-long learning -- learning never ends as long as you are alive.

My main focus for sharing this is ...]]></description><link>https://nandaa.fyi/technical-books-for-2024</link><guid isPermaLink="true">https://nandaa.fyi/technical-books-for-2024</guid><category><![CDATA[linux-internals]]></category><category><![CDATA[windows-internals]]></category><category><![CDATA[reading]]></category><category><![CDATA[Computer Science]]></category><dc:creator><![CDATA[Anthony Nandaa]]></dc:creator><pubDate>Tue, 26 Dec 2023 18:08:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/X5gDoysLbBc/upload/666dd36fc899de1493bedab4bea38683.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I strongly advocate for <em>learning in the public</em> due to several compelling reasons:</p>
<ol>
<li><p>One or two people can learn from you.</p>
</li>
<li><p>Builds up the <em>culture of life-long learning</em> -- learning never ends as long as you are alive.</p>
</li>
<li><p>My main focus for sharing this is for the young folks coming after us, especially those in college right now. <em>Don't waste your college life</em>, some of the books I'm reading now I wish I read while in campus when <em>I had so much time</em> (I wish) and less pressures of life :)</p>
</li>
</ol>
<p>Here is a list of books, <a target="_blank" href="https://www.bible.com/bible/59/JAS.4.13-16.ESV"><em>God willing</em></a><em>,</em> I intend to finish reading in 2024 (and 2025) -- <a target="_blank" href="https://profnandaa.notion.site/c05c95bda2994c34846b36ad88c0a94d?v=a3c50046675641debdf7c2cb78fdf07a&amp;pvs=4">https://profnandaa.notion.site/c05c95bda2994c34846b36ad88c0a94d?v=a3c50046675641debdf7c2cb78fdf07a&amp;pvs=4</a></p>
<p><a target="_blank" href="https://profnandaa.notion.site/c05c95bda2994c34846b36ad88c0a94d?v=a3c50046675641debdf7c2cb78fdf07a"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703613040244/f028b3ee-15a9-4e8a-9917-32fb3126d772.png" alt class="image--center mx-auto" /></a></p>
<p>Please note that this is a lopsided list mainly due to my current system-engineering-heavy work. I encourage you to create your own too. For a good list of great recommended books, check this out: <a target="_blank" href="https://github.com/csklub/swe-essential-books/tree/main">csklub/swe-essential-books: The canonical and partly opinionated list of books that every software engineer should read in their lifetime. (github.com)</a>. You won't go wrong with any random pick from this list.</p>
<blockquote>
<p><strong><mark>UPDATE: </mark></strong> I'll be covering some these books on the <strong>blackbored.</strong> Youtube channel. If you would like to come over and discuss any technical book you are reading, send me an email on <strong>books [at] bored.black</strong></p>
</blockquote>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=L3TyKufJHiA">https://www.youtube.com/watch?v=L3TyKufJHiA</a></div>
<p> </p>
<blockquote>
<p><strong><mark>UPDATE(2):</mark></strong> I didn’t get to complete all the 32 books in 2024, completed roughly 6 books, I’m giving it a good shot in 2025.</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[C Pointers Demystified]]></title><description><![CDATA[Introduction
Pointers are variables that store the address of another variable.

Allow us to indirectly access variables (i.e. we can talk about its address rather than its value)

Importance of Pointers:

More flexible pass-by-reference.

Manipulate...]]></description><link>https://nandaa.fyi/c-pointers-demystified</link><guid isPermaLink="true">https://nandaa.fyi/c-pointers-demystified</guid><category><![CDATA[Computer Science]]></category><category><![CDATA[c programming]]></category><category><![CDATA[pointers in c]]></category><dc:creator><![CDATA[Anthony Nandaa]]></dc:creator><pubDate>Sat, 16 Dec 2023 02:32:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/Im7lZjxeLhg/upload/8075db2c510d839fbbf34c5cf209def5.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p><strong>Pointers</strong> are variables that store the address of another variable.</p>
<ul>
<li>Allow us to <em>indirectly</em> access variables (i.e. we can talk about its address rather than its <em>value</em>)</li>
</ul>
<h3 id="heading-importance-of-pointers">Importance of Pointers:</h3>
<ul>
<li><p>More flexible pass-by-reference.</p>
</li>
<li><p>Manipulate complex data structures efficiently, even if their data is scattered in deferent memory locations.</p>
</li>
<li><p>Use polymorphism - calling functions on data without knowing exactly what kind of data it is. (<em>see "pointers and function" section</em>)</p>
</li>
</ul>
<h2 id="heading-declaring-pointers">Declaring Pointers</h2>
<p>Simply <code>&lt;type&gt; *&lt;var_name&gt;;</code>, e.g.</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> *ptr;
</code></pre>
<p>The pointer can then be initialized to a memory address for a variable, which is found by using <code>&amp;</code>, e.g.</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> x = <span class="hljs-number">20</span>;
<span class="hljs-keyword">int</span> *px = &amp;x;
</code></pre>
<p>To illustrate this with a diagram and code, consider the following simple program:</p>
<pre><code class="lang-c"><span class="hljs-comment">// pointers1.c</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">int</span> x = <span class="hljs-number">20</span>;
    <span class="hljs-keyword">int</span> *px = &amp;x;
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"ptr: %p -&gt; addr %p has: %d\n"</span>, &amp;px, px, x);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>When compiled with <code>gcc pointers1.c</code> and run, you get something similar to this:</p>
<pre><code class="lang-plaintext">ptr: 0x7ffec8780c10 -&gt; addr 0x7ffec8780c0c has: 20
</code></pre>
<p><em>the pointer</em> <code>px</code> is in address <code>0x7ffec8780c10</code>, pointing 4 bytes away at address <code>0x7ffec8780c0c</code> that contains <code>x</code>; consider the diagram below</p>
<p><img src="https://user-images.githubusercontent.com/261265/213256470-873f6f21-a967-4b49-9858-9608ada9d525.png" alt="memory_model" /></p>
<blockquote>
<p>ℹ <strong>Note</strong><br />My own preference and the prevalent practice is to put the <code>*</code> just before the name of the variable as opposed to putting it after the type, as some do. The later is also misleading when you have a list of variables in one line, e.g.<br /><code>int *ptr, x, y</code> vs. <code>int* ptr, x, y</code>.<br />(<code>x</code> and <code>y</code> are just integers but the later may make it look like all are pointers!)</p>
</blockquote>
<h2 id="heading-dereferencing-pointers">Dereferencing Pointers</h2>
<ul>
<li><p>To dereference a pointer is to get the value of what the pointer is pointing to.</p>
</li>
<li><p>We use <code>*&lt;pointer_pointer_var_name&gt;</code>, for example:</p>
<pre><code class="lang-c">  <span class="hljs-keyword">int</span> x = <span class="hljs-number">30</span>;
  <span class="hljs-keyword">int</span> *px = &amp;x;
  *px = <span class="hljs-number">40</span>; <span class="hljs-comment">// changes x</span>
  <span class="hljs-comment">// print memory address of where px is pointing </span>
  <span class="hljs-comment">// at (px) and the value in the address (*px)</span>
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%p -&gt; %d\n"</span>, px, *px); 
  <span class="hljs-comment">// also note that the pointer also is stored </span>
  <span class="hljs-comment">// somewhere in memory and we can get its location </span>
  <span class="hljs-comment">// by &amp;px, e.g.</span>
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%p\n"</span>, &amp;px);
  <span class="hljs-comment">// so</span>
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%p stores -&gt; %p (px), which stores -&gt; %d (x)\n"</span>, &amp;px, px, *px);
</code></pre>
</li>
</ul>
<h2 id="heading-null-pointers">Null Pointers</h2>
<ul>
<li><p>Any pointer set to <code>0</code> is called a <em>null pointer</em>, since there's no memory location <code>0</code>, it is an invalid pointer.</p>
</li>
<li><p>Dereferencing such a pointer leads to a runtime error. One should check whether the pointer is null before dereferencing it.</p>
<pre><code class="lang-c">  <span class="hljs-keyword">int</span> *py = <span class="hljs-number">0</span>; <span class="hljs-comment">// or int *py = NULL;</span>
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d\n"</span>, *py); <span class="hljs-comment">// seg-fault!</span>
</code></pre>
</li>
<li><p>You may ask, what's the point for <em>null pointers</em>? Null pointers are very important for initializing pointers which will point to proper memory addresses later on, but they are not yet determined. If we declared <code>int *pz;</code> without initializing it, the compiler (GCC in my case), will point <code>pz</code> to a random memory address ("allocate"). However, this is not guaranteed, will <em>seg-fault</em> too, sometimes.</p>
<pre><code class="lang-c">  <span class="hljs-keyword">int</span> *pz;
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d\n"</span>, *pz);
</code></pre>
</li>
</ul>
<h2 id="heading-pointers-and-arrays">Pointers and Arrays</h2>
<ul>
<li><p>An array is a list of values arranged sequentially in memory.</p>
</li>
<li><p>The variable name of the array is usually <em>a special kind of pointer</em>, it can decay into a pointer; as we will see below:</p>
<pre><code class="lang-c">  <span class="hljs-keyword">int</span> arr[] = { <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span> }; <span class="hljs-comment">// `arr` decays into int* (int pointer)</span>
</code></pre>
</li>
<li><p>Therefore, <code>arr</code> in the example above is equivalent to an <code>int*</code>. <code>arr</code> is a pointer pointing to the beginning of the array.</p>
</li>
<li><p>To get the first element of the array, we will use <code>*arr</code>.</p>
</li>
<li><p>To get the second element of the array, we use <code>*(arr + 1)</code></p>
</li>
<li><p>Therefore to get the <em>nth</em> element of the array we will use <code>*(arr + n - 1)</code>.</p>
<pre><code class="lang-c">  <span class="hljs-keyword">int</span> arr[] = { <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span> };
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d, %d, %d\n"</span>, *arr, *(arr + <span class="hljs-number">1</span>), *(arr + <span class="hljs-number">2</span>));
</code></pre>
</li>
<li><p>Let's look at an example for summing up numbers in an array:</p>
<pre><code class="lang-c">  <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">sumArray</span><span class="hljs-params">(<span class="hljs-keyword">int</span> *arr, <span class="hljs-keyword">int</span> sz)</span>
  </span>{
      <span class="hljs-keyword">int</span> sum = <span class="hljs-number">0</span>;
      <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; sz; ++i)
      {
          sum += *(arr + i); <span class="hljs-comment">// or sum += arr[i]</span>
      }
      <span class="hljs-keyword">return</span> sum;
  }
</code></pre>
<ul>
<li><p><code>sumArray</code> takes in a pointer to an array and the size of that array.</p>
</li>
<li><p>However, there's not way of telling (AFAIK) that that pointer truly points to an array, it could as well just be an ordinary pointer to an int. For instance of if we gave <code>x</code> (from our example in the beginning) to this function, it will compile correctly and it may even run without a seg-fault!</p>
<pre><code class="lang-c">  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"fake sum -&gt; %d\n"</span>, sumArray(px, <span class="hljs-number">3</span>));
  <span class="hljs-comment">// if you thought that's enough, try this!</span>
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"fake sum -&gt; %d\n"</span>, sumArray(px, <span class="hljs-number">300</span>));
  <span class="hljs-comment">// 300 contiguous memory addresses</span>
  <span class="hljs-comment">// from px are summed up</span>
</code></pre>
</li>
<li><p>This is the same reason why strings (array of chars) have a sentinel value <code>\0</code> at the end that signifies the end of the array (aka, <em>the null terminator</em>).</p>
</li>
</ul>
</li>
</ul>
<blockquote>
<p><strong>ℹ Note</strong><br />In the next section, we will look at pointer-to-pointer. It is worth noting here that <code>&amp;arr</code> in our example above will be an <code>int**</code> (pointer to pointer, or address of a pointer <code>arr</code>), since <code>arr</code> is <code>int*</code>.</p>
</blockquote>
<h3 id="heading-incrementing-pointers">Incrementing Pointers</h3>
<p>Since pointers point to memory addresses which are contiguous, it is therefore possible to increment a pointer to move to the next address. The pointer will step according to it's size, e.g. <code>int *</code> will be stepping 32 bits (4 bytes) each.</p>
<p>Let's look at an example:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> arr[] = { <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span> };
<span class="hljs-keyword">int</span> *p = arr;   <span class="hljs-comment">// points to the first element in arr</span>
p++;            <span class="hljs-comment">// now p is pointing at the 2nd element</span>
<span class="hljs-built_in">printf</span>(<span class="hljs-string">"p -&gt; %d\n"</span>, *p);
<span class="hljs-built_in">printf</span>(<span class="hljs-string">"p -&gt; %d\n"</span>, *(++p)); <span class="hljs-comment">// pointer now pointing to the 3rd</span>
</code></pre>
<p>This should be done strictly for <em>guaranteed</em> contiguous memory addresses, i.e. arrays, and you should know where the end is (where to stop).</p>
<h3 id="heading-character-pointers">Character Pointers</h3>
<p>In C, we create a <em>string</em> by using an array of characters (loosely). A pointer pointing to this array is therefore a character pointer.</p>
<blockquote>
<p><em>It will be insane to just have one pointer pointing to one char, what's the point?</em></p>
</blockquote>
<p>Now, how do we tell we have reached the end of our "string"? We use a null terminator <code>\0</code>. That is when it is a proper string, else, it's just an array of characters.</p>
<p>Let's look at an example:</p>
<pre><code class="lang-c"><span class="hljs-keyword">char</span> s[] = { <span class="hljs-string">'h'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'l'</span>, <span class="hljs-string">'l'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'\0'</span> };
<span class="hljs-keyword">char</span> *ps = s;
<span class="hljs-comment">// notice that the length of the array will always be +1 the length of the</span>
<span class="hljs-comment">// string, because of the \0</span>
<span class="hljs-built_in">printf</span>(<span class="hljs-string">"%s, str length = %ld, array length = %d\n"</span>, ps, <span class="hljs-built_in">strlen</span>(ps), <span class="hljs-keyword">sizeof</span>(sl));
<span class="hljs-comment">// a shorter way to initalize this:</span>
<span class="hljs-keyword">char</span> *ps2 = <span class="hljs-string">"another hello"</span>; <span class="hljs-comment">// using double quotes to denote string</span>
<span class="hljs-built_in">printf</span>(<span class="hljs-string">"%s, length = %ld\n"</span>, ps2, <span class="hljs-built_in">strlen</span>(ps2));
</code></pre>
<p>As we had mentioned earlier, there is no way to know you have reached the end of an array, unless you put a <em>sentinel</em> value to mark the end. We use <code>\0</code> to mark the end of a string. For instance, this:</p>
<pre><code class="lang-c"><span class="hljs-keyword">char</span> hackedStr[] = { <span class="hljs-string">'g'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'\0'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'d'</span>};
<span class="hljs-built_in">printf</span>(<span class="hljs-string">"%s, str length = %ld, array length = %ld\n"</span>, hackedStr, <span class="hljs-built_in">strlen</span>(hackedStr), <span class="hljs-keyword">sizeof</span>(hackedStr));
</code></pre>
<h2 id="heading-pointer-to-pointer">Pointer to Pointer</h2>
<p>We can have a pointer pointing to a pointer, and even another pointer pointing to the/that pointer (<code>pointer -&gt; pointer -&gt; pointer</code>).</p>
<p>Let's look at a simple example:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> y = <span class="hljs-number">10</span>;
<span class="hljs-keyword">int</span> *py = &amp;y;
<span class="hljs-keyword">int</span> **ppy = &amp;py;
<span class="hljs-keyword">int</span> ***pppy = &amp;ppy; <span class="hljs-comment">// we can go on and on</span>

<span class="hljs-built_in">printf</span>(<span class="hljs-string">"%p -&gt; %p -&gt; %p -&gt; %d\n"</span>, pppy, ppy, py, y);
<span class="hljs-comment">// we can deference any to get to our int value</span>
<span class="hljs-comment">// notice the symetry in the *</span>
<span class="hljs-comment">// as per the declaration</span>
<span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d, %d, %d\n"</span>, ***pppy, **ppy, *py);
<span class="hljs-comment">// likewise you can modify through indirection</span>
***pppy = <span class="hljs-number">40</span>;
<span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d\n"</span>, y);
</code></pre>
<p>Likewise, you can have a pointer that points to the array pointer, eg:</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> arr2[] = { <span class="hljs-number">2</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span> };
<span class="hljs-keyword">int</span> *p2 = arr2;
<span class="hljs-keyword">int</span> **ppArr = &amp;p2;
<span class="hljs-built_in">printf</span>(<span class="hljs-string">"1st element in arr: %d\n"</span>, **ppArr);
<span class="hljs-built_in">printf</span>(<span class="hljs-string">"2nd element in arr: %d\n"</span>, *(*ppArr + <span class="hljs-number">1</span>)); <span class="hljs-comment">// notice the brackets</span>
</code></pre>
<blockquote>
<p><em>We will see why this is important when we look at the the next section on passing by value and by reference.</em></p>
</blockquote>
<h2 id="heading-pointers-and-functions">Pointers and Functions</h2>
<h3 id="heading-passing-by-value-vs-by-reference">Passing by Value vs. by Reference</h3>
<p>A pointer is a <em>value</em> too, only that that value is a reference. <em>Let that sink in</em>.</p>
<p>Therefore you can pass a pointer to a function <em>by value</em> or <em>by reference</em>. Reference here will be a pointer to that pointer.</p>
<p>To illustrate this, let's look at the following example:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">swap1</span><span class="hljs-params">(<span class="hljs-keyword">int</span> *a, <span class="hljs-keyword">int</span> *b)</span>
</span>{
    <span class="hljs-keyword">int</span> *temp = a;
    a = b;
    b = temp;
}

<span class="hljs-comment">// the above function is for illustration purpose only</span>
<span class="hljs-comment">// the actual swapping function should be:</span>
<span class="hljs-comment">/*
void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
*/</span>

<span class="hljs-keyword">int</span> m = <span class="hljs-number">30</span>, n = <span class="hljs-number">20</span>;
<span class="hljs-keyword">int</span> *pm = &amp;m, *pn = &amp;n;
swap1(pm, pn); <span class="hljs-comment">// passed by value</span>
<span class="hljs-built_in">printf</span>(<span class="hljs-string">"m -&gt; %d, n -&gt; %d\n"</span>, *pm, *pn); <span class="hljs-comment">// no swap done!</span>
</code></pre>
<p>Basically, we just passed by value (a copy of the pointers) to the function, and therefore, our original pointers remained untouched.</p>
<p>We have to pass by refeference (a pointer to the pointer):</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">swap2</span><span class="hljs-params">(<span class="hljs-keyword">int</span> **a, <span class="hljs-keyword">int</span> **b)</span>
</span>{
    <span class="hljs-keyword">int</span> *temp = *a;
    *a = *b;
    *b = temp;
}

<span class="hljs-keyword">int</span> m = <span class="hljs-number">30</span>, n = <span class="hljs-number">20</span>;
<span class="hljs-keyword">int</span> *pm = &amp;m, *pn = &amp;n;

swap2(&amp;pm, &amp;pn);
<span class="hljs-built_in">printf</span>(<span class="hljs-string">"m -&gt; %d, n -&gt; %d\n"</span>, *pm, *pn); <span class="hljs-comment">// now swap done</span>
</code></pre>
<h3 id="heading-returning-pointers">Returning Pointers</h3>
<p>As you may have known by now, you can pass pointers to functions and also you can return pointers from a function.</p>
<p>The following example is <strong>very buggy</strong> but it passes the point across -- that you can return a pointer from a function. I leave the exercise of finding out why it's buggy to you, to save on the space that I'd have to use to explain how the <em>function call-stack</em> works:</p>
<blockquote>
<p><em>We will revisit this example when we look at</em> <code>malloc</code>.</p>
</blockquote>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">int</span>* <span class="hljs-title">return_ptr</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">int</span> x = <span class="hljs-number">30</span>;
    <span class="hljs-keyword">return</span> &amp;x; <span class="hljs-comment">// pointer to x (local)</span>
}
</code></pre>
<h2 id="heading-pointer-to-functions">Pointer to Functions</h2>
<blockquote>
<p><em>I'd initially planned to cover this topic as a sub-section of</em> <strong><em>Pointers and Functions</em></strong> <em>but I think it deserves it's own section.</em></p>
</blockquote>
<p>This concept is not covered in most books but it is such a powerful concept. With pointers to functions, you can now pass functions to other functions (by reference).</p>
<p>This is the general format on how you declare such a pointer:</p>
<pre><code class="lang-plaintext">&lt;return_type&gt; (*&lt;name_of_ptr&gt;)(&lt;type_of_params,...&gt;) = &amp;&lt;the_function_pointed_to&gt;
</code></pre>
<p>For example, for a function with a signature like <code>int sum(int x, int y)</code>, this is how we will write its pointer:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">sum</span><span class="hljs-params">(<span class="hljs-keyword">int</span> x, <span class="hljs-keyword">int</span> y)</span></span>;
<span class="hljs-keyword">int</span> (*sum_ptr)(<span class="hljs-keyword">int</span>, <span class="hljs-keyword">int</span>) = &amp;sum;

<span class="hljs-comment">// and then calling</span>
<span class="hljs-keyword">int</span> z = (*sum_ptr)(<span class="hljs-number">30</span>, <span class="hljs-number">50</span>);
</code></pre>
<p>And thefore you can pass it to another function thus:</p>
<pre><code class="lang-c">
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">do_op</span><span class="hljs-params">(<span class="hljs-keyword">int</span> (*fn_ptr)(<span class="hljs-keyword">int</span>, <span class="hljs-keyword">int</span>))</span> </span>{
    <span class="hljs-keyword">int</span> x = <span class="hljs-number">30</span>, y = <span class="hljs-number">40</span>;
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d + %d = %d\n"</span>, x, y, (*fn_ptr)(x, y));
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-comment">// ...</span>
    do_op(&amp;sum);
    <span class="hljs-comment">// ...</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Let's look at another example of a <em>callback</em> function <code>print(int)</code> passed to another function <code>mul</code> which multiplies two numbers and then calls the <code>print</code> function which prints out the results. So we leave the caller decide on how they want to print, formatting, etc.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">print</span><span class="hljs-params">(<span class="hljs-keyword">int</span> prod)</span> </span>{
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"The product = %d\n"</span>, prod);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">mul</span><span class="hljs-params">(<span class="hljs-keyword">int</span> x, <span class="hljs-keyword">int</span> y, <span class="hljs-keyword">void</span> (*print_fn)(<span class="hljs-keyword">int</span>))</span> </span>{
    <span class="hljs-keyword">int</span> prod = x * y;
    (*print_fn)(prod);
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    mul(<span class="hljs-number">20</span>, <span class="hljs-number">30</span>, &amp;print);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<h2 id="heading-malloc-calloc-and-free"><code>malloc</code>, <code>calloc</code> and <code>free</code></h2>
<h4 id="heading-malloc"><code>malloc</code></h4>
<p><code>malloc()</code> is the function used for dynamic allocation. This allocation is done on the heap. All the allocations we've seen so far up to this point, have been on the stack, and therefore deallocation is done immediately the function returns/exits.</p>
<p>The syntax for <code>malloc</code> is <code>void *malloc(size_t size)</code> -- basically it takes in the size (in bytes) of the memory allocation to be done and returns and <code>void*</code> pointer. You can then type cast <code>void *</code> to the relevant type of the allocation. However, as far as <code>malloc</code> is concerned, all it does is get you a contiguous memory on the heap of size <code>size</code> and returns a pointer pointing to the first byte of that location.</p>
<p>The typical convention is to use <code>number_of_elements * sizeof(type)</code> in the place of `size):</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> *m_ptr = (<span class="hljs-keyword">int</span> *)<span class="hljs-built_in">malloc</span>(<span class="hljs-number">10</span> * <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">int</span>));
<span class="hljs-keyword">if</span> (m_ptr == <span class="hljs-literal">NULL</span>) {
    <span class="hljs-comment">// allocation faield</span>
    <span class="hljs-comment">// handle error</span>
}
</code></pre>
<p>There is no guarantees that the allocation will always succeed, it may fail, especially due to lack of enough memory. Therefore, it is important to check that the pointer returned is not <code>NULL</code>.</p>
<p><code>malloc</code> does not zero out the memory, so, you might end up with garbage initially in the memory location. Try it out to see for yourself.</p>
<h4 id="heading-calloc"><code>calloc</code></h4>
<p><code>calloc</code> is more of syntactic sugar on top of <code>malloc</code>, it dynamically allocates memory and initializes all bytes in the allocated memory to zero; and also provides for <code>num_of_elements</code> in it's signature as you will see shortly.</p>
<p>Basically <code>calloc</code> uses <code>malloc</code> to allocate memory, but it does a step further by also initializing all the allocated memory to zero.</p>
<p>The syntax is <code>void *calloc(size_t num_of_elements, size_t element_size)</code></p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> *c_ptr = (<span class="hljs-keyword">int</span> *)<span class="hljs-built_in">calloc</span>(<span class="hljs-number">10</span>, <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">int</span>));
<span class="hljs-keyword">if</span> (c_ptr == <span class="hljs-literal">NULL</span>) {
    <span class="hljs-comment">// allocation failed</span>
    <span class="hljs-comment">// handle error</span>
}
</code></pre>
<p><code>free</code></p>
<p>The previous two code-snippets are buggy as stand-alone (has <em>memory leaks</em>). Whenever you allocate memory, it is your responsibility to free it. There's no free lunch as what we get with allocations on the stack which are cleared by the operating systems as soon as the function returns/exits. This is where <code>free()</code> comes in.</p>
<p><code>free</code> is used to deallocate memory previously allocated by <code>malloc</code> or <code>calloc</code>. It basically releases the memory pointed to by the given pointer. Syntax: <code>void free(void *ptr)</code></p>
<pre><code class="lang-c"><span class="hljs-comment">// for the previous allocation done by malloc and calloc</span>
<span class="hljs-comment">// we can free them once we're done with them</span>
<span class="hljs-built_in">free</span>(m_ptr);
<span class="hljs-built_in">free</span>(c_ptr);
</code></pre>
<h2 id="heading-memory-leaks">Memory Leaks</h2>
<p>Memory leaks occur when you (unintentionally) fail to release or deallocate memory. As a result, the allocated memory remains inaccessible and unusable even after the program (or the program portion) has finished executing.</p>
<p>For a long-running <em>user-space</em> process for example, leaks can keep growing until the memory is exhausted at last, where the operating system will can then step in and kill the process. When it comes to <em>kernel-space</em> processes, it's a different story, leaks can essentially choke the whole system where you end with a <code>panic</code> in Linux for example or a BSOD (<em>blue screen of death</em>) in Windows.</p>
<p>For a short-running <em>user-space</em> processes, leaks can go undetected since the side-effects may not be that visible.</p>
<p>Let's look at a simple example here:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdlib.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-comment">// allocate memory for an integer</span>
    <span class="hljs-keyword">int</span> *ptr = (<span class="hljs-keyword">int</span>*)<span class="hljs-built_in">malloc</span>(<span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">int</span>));
    <span class="hljs-comment">// check if memory allocation succeeded</span>
    <span class="hljs-keyword">if</span> (ptr == <span class="hljs-literal">NULL</span>) {
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
    }

    <span class="hljs-comment">// proceed to use the allocated memory in the program</span>

    <span class="hljs-comment">// but at the end, forget to free the memory</span>
    <span class="hljs-comment">// missing: free(ptr);</span>
}
</code></pre>
<p>Luckily now, we have very good static code analysis tools that can help detect such defects like memory leaks.</p>
<h2 id="heading-further-reading">Further Reading</h2>
<p>I'd encourage you to take a look at a number of opensource C source-codes and see how pointers are used. For a start, you can check out the following:</p>
<ul>
<li><p><a target="_blank" href="https://elixir.bootlin.com/linux/latest/source">Linux source-code</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/git/git">Git source-code</a></p>
</li>
</ul>
<blockquote>
<p>💡 <em>This series is a WIP, keep checking back for updates. Will try do a changelog</em> <em>This blog can be</em> <a target="_blank" href="https://github.com/profnandaa/profnandaa.github.io/pull/2"><em>reviewed inline here</em></a><em>, I will appreciate your suggestions, comments and nitpicks.</em></p>
</blockquote>
]]></content:encoded></item></channel></rss>