<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sayak Kundu on Medium]]></title>
        <description><![CDATA[Stories by Sayak Kundu on Medium]]></description>
        <link>https://medium.com/@sayak3103?source=rss-5c977f55ef55------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*FfilJY0d54llW3gh_1BoDA.jpeg</url>
            <title>Stories by Sayak Kundu on Medium</title>
            <link>https://medium.com/@sayak3103?source=rss-5c977f55ef55------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 15:39:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sayak3103/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[C++ Smart Pointers Basics]]></title>
            <link>https://medium.com/@sayak3103/c-smart-pointers-basics-37df8818a4f4?source=rss-5c977f55ef55------2</link>
            <guid isPermaLink="false">https://medium.com/p/37df8818a4f4</guid>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[c-plus-plus-language]]></category>
            <category><![CDATA[smart-pointer]]></category>
            <dc:creator><![CDATA[Sayak Kundu]]></dc:creator>
            <pubDate>Mon, 06 Jun 2022 22:53:26 GMT</pubDate>
            <atom:updated>2022-06-07T13:16:17.101Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*06cLUtNhAwjxSsy3OyuYeA.jpeg" /></figure><p>As I transitioned to coding in C++ after 9 years of Java, I was struggling with several language constructs that I was not familiar with from college. One such language feature was smart-pointers. Hence, I am compiling a short note on what I learnt about them if it is of any help to others making a similar jump.</p><h3><strong>Memory Leaks and why it is bad</strong></h3><p>When a piece of code executes, you can have memory blocks allocated in the stack (by the compiler) or in the heap (by explicit instruction in the code). For the memory block allocated in the heap, you have references to the block stored in variables. These variables are stored in the stack. As the variable’s scope of declaration is exited, they get deleted automatically. The problem occurs when you have the variable deleted but the block of heap memory it had a reference to was not de-allocated. Since the variable gone, its very hard to know where the allocated block was and reclaim that space. Hence you have “leaked” the block of memory and can’t re-use it.</p><p>In Java, the JVM runs a garbage collector which periodically scans for such lost blocks and frees them up. C++ does not have that and you are required to manage memory by yourself. So, whenever you allocate some memory in the heap with new, malloc etc you are expected to free up that space before you forget about that memory in your code. Naturally, this is very prone to human error and this is where smart-pointers can help you.</p><p>However, you should not think of smart-pointers as C++’s answer to garbage collector. It is rather built with a broader intent of <em>expressing ownership of the memory block allocated in heap. The memory leak prevention happens as a consequence of this ownership management.</em> It is important to understand this intent to prevent inappropriate use of this feature.</p><h3><strong>What do we mean by expressing ownership</strong></h3><p>When you allocate a chunk of heap-space dynamically by creating a new object, you get a reference to that memory location. Using this reference you can access/manipulate the object. Only you can do this since only you have the reference. This is called ownership of the object. If you chose to share the ownership with some function or thread then after you have forgotten about this object (the variable storing the reference to objects address on heap is deleted) there is still someone owning the object (and has its reference!). Otherwise, if you were the unique owner then after you forget about the object - the object is of no use and the associated heap space should be deallocated.</p><p>The above idea can be expressed in C++ using unqiue_ptr and shared_ptr from &lt;memory&gt; header.</p><h3>unique_ptr</h3><p>If you are pointing to an object with a unique_ptr, then you signal the compiler that at any point of time the object can have maximum one owner. If there are no owners, the object can (and will) be deleted and its memory freed up.</p><pre>void foo(std::unique_ptr&lt;int&gt; q) {<br>    std::cout &lt;&lt; &quot;\\n within foo q is pointing to : &quot; &lt;&lt; q;<br>}</pre><pre>int main() {<br>	auto q = std::unique_ptr&lt;int&gt;(new int(4));<br>	std::cout &lt;&lt; &quot;\\n q is now : &quot; &lt;&lt; q;<br>	foo(std::move(q));<br>	std::cout &lt;&lt; &quot;\\n q is now : &quot; &lt;&lt; q;<br>	return 0;<br>}</pre><p>If I run the above code (with leaks -atExit to enquire about memory leaks):</p><pre>q is now : 0x600003a4c040 // where our object is in the heap!<br> within foo q is pointing to : 0x600003a4c040<br> q is now : 0x0<br>----<br>leaks Report Version: 4.0<br>Process 10264: 211 nodes malloced for 16 KB<br>Process 10264: 0 leaks for 0 total leaked bytes.</pre><p>Two things to note over here:</p><ol><li>Even though you did not deallocate the memory held by q, there is no leak. It is automatically cleaned up by the runtime.</li><li>Since you were using a unique pointer, after the pointer was passed to foo, you let go of the ownership and q points to 0x0 instead of 0x600003a4c040. With this feature, you can <em>code defensively</em> in your program to enforce only a unique entity at a time has read/write access to a memory block. This is also why, unique_ptrclass does not have a copy c’tor and you need to std::move() it instead of passing it as a parameter.</li></ol><h3>shared_ptr</h3><p>If you are pointing to an object with a shared_ptr, the runtime keeps a count of the number of owners for the memory block and frees the space only when the count decrements to zero. Explaining with an example,</p><pre>void foo(std::shared_ptr&lt;int&gt; p) {<br>    std::cout &lt;&lt; &quot;\\n within foo p is pointing to : &quot; &lt;&lt; p;<br>    std::cout &lt;&lt; &quot;\\n p&#39;s reference count is : &quot; &lt;&lt; p.use_count();<br>}</pre><pre>int main() {<br>    auto p = std::shared_ptr&lt;int&gt;(new int(2));<br>    std::cout &lt;&lt; &quot;\\n p is now : &quot; &lt;&lt; p;<br>    std::cout &lt;&lt; &quot;\\n p&#39;s reference count is : &quot; &lt;&lt; p.use_count();<br>    foo(p);<br>    std::cout &lt;&lt; &quot;\\n p is now : &quot; &lt;&lt; p;<br>    std::cout &lt;&lt; &quot;\\n p&#39;s reference count is : &quot; &lt;&lt; p.use_count();<br>    return 0;<br>};</pre><p>if I run the above code (with leaks -atExit to enquire about memory leaks):</p><pre>p is now : 0x600002ff0040<br> p&#39;s reference count is : 1<br> within foo p is pointing to : 0x600002ff0040<br> p&#39;s reference count is : 2<br> p is now : 0x600002ff0040<br> p&#39;s reference count is : 1<br>----</pre><pre>leaks Report Version: 4.0<br>Process 10448: 211 nodes malloced for 16 KB<br>Process 10448: 0 leaks for 0 total leaked bytes.</pre><p>Like the above example there is no memory leak.</p><p>But unlike unique_ptr, you can share the memory allocated with others. foo() and main() both holds the reference to the memory block and the runtime appropriately maintains the count of owners in the use_count attribute in the pointer.</p><p>Consequently if you call sizeof() , you will notice that the space consumed by a unique_ptr is less than the space consumed by a shared_ptr by the amount of space needed to store use_count 🙂</p><h3>Closing notes</h3><p>Even though this is nowhere a comprehensive article on smart-pointers, I wanted to emphasise how we should think more than garbage-collection and think about ownership of objects when exploring smart-pointers. I will encourage you to also learn about weak_ptr in the &lt;memory&gt; header.</p><p>Also, the picture with this post is of few boats on Thames taken from the Westminster bridge and not related in anyway to smart-pointers.</p><p>Lastly, please consider sharing this article if you think it might useful. Feel free to connect with me or comment to discuss further as well.</p><h3>References</h3><ol><li><a href="https://en.cppreference.com/w/cpp/memory/shared_ptr">https://en.cppreference.com/w/cpp/memory/shared_ptr</a></li><li><a href="https://en.cppreference.com/w/cpp/memory/unique_ptr">https://en.cppreference.com/w/cpp/memory/unique_ptr</a></li><li><a href="https://docs.microsoft.com/en-us/cpp/cpp/smart-pointers-modern-cpp?view=msvc-170">https://docs.microsoft.com/en-us/cpp/cpp/smart-pointers-modern-cpp?view=msvc-170</a></li><li><a href="https://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one">https://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37df8818a4f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Few important points on habit-building]]></title>
            <link>https://medium.com/@sayak3103/few-important-points-on-habit-building-b7d004dbbd8e?source=rss-5c977f55ef55------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7d004dbbd8e</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[habit-building]]></category>
            <category><![CDATA[habits]]></category>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[self-improvement]]></category>
            <dc:creator><![CDATA[Sayak Kundu]]></dc:creator>
            <pubDate>Sun, 10 May 2020 17:20:51 GMT</pubDate>
            <atom:updated>2020-05-10T17:20:51.424Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3YoCSBDVPv9WJ5aW028psQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@drew_beamer?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Drew Beamer</a> on <a href="https://unsplash.com/s/photos/habits?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This article discusses few unintuitive, yet highly effective points on habit-building from the book titled <a href="https://www.amazon.com/Atomic-Habits-Proven-Build-Break/dp/0735211299">Atomic Habits — An Easy &amp; Proven Way to Build Good Habits &amp; Break Bad Ones</a>, by James Clear. This is not a comprehensive summary of the book, the below points are just the ones which moved me the most.</p><p><strong>Identify yourself with the habit</strong></p><p>The good habits we want to pick up can be result of calculating backwards from a Goal we want to achieve. For example, if the goal is something like weighing below a certain number on the weighing-scale, we formulate a plan to achieve that goal and figure out that developing habits of healthy eating and regular workouts are indispensable for success. However, changing any preset human behaviour is hard. While forming these habits if we keep telling ourselves that we are undertaking the hardship to attain the goal (of weighing below the certain number in mind for our example) the mind gets programmed to believe the changes as well as the hardships are temporary. Consequently, sooner or later when we do reach that goal there is little motivation or reason left to make us stick to the hardship and the habit goes for a toss.</p><p>James Clear, introduces the idea of building <em>a proud identity</em> around the habit we want to form to tackle this problem. In our above example, this would mean taking pride in being called fitness-conscious or health-conscious which would give us the incentive to stick to our healthy eating and exercising habits, that outlives the goal of weighing a certain weight.</p><p>Moreover, this shift of thought might make the habit development more fulfilling because the results come sooner. We start believing that we are health-conscious after a week of healthy eating even though we will weigh the desired weight after a month or two.</p><p>This shift of thought also forces us to filter out habits that we might not be cut out for. James Clear, mentions that any habit which is completely incongruent to our personality will be very difficult to last, no matter how satisfying the results are. The charm of the reaching the goal is very ephemeral.</p><p>More examples around this:</p><ul><li>if you want to pick up a reading habit — develop pride in being called someone who likes to read</li><li>if you want to develop a running habit — take pride in being called a runner and work towards that.</li></ul><p><strong>Construct a habit-loop</strong></p><p>The habit-loop is a popular concept found all over the internet.</p><figure><img alt="The Habit Loop" src="https://cdn-images-1.medium.com/max/271/1*F2dxHuPrZUAAKtVKsvzxfQ.jpeg" /></figure><p>The above diagram depicts the habit-loop.</p><ul><li>The <strong><em>Response</em></strong> is the activity that we perform as a habit.</li><li>The response is kicked-in within our brain by some <strong><em>Stimulus</em></strong><em> </em>that we face<em>. </em>For example the response of ordering a dessert after a sumptuous meal might be the salty aftertaste on our palate.</li><li>The <strong><em>Reward</em></strong> is the outcome of the response; feeling the cold and sweet ice-cream in our mouth, for our above example.</li></ul><p>Eventually our brain gets programmed with many habit-loops based on repeatedly performing these sequence of actions in our daily lives. Once a loop is formed, the brain puts the response to the stimulus into an automation and doesn’t involve itself as long as the loop is maintained. (In fact, it is believed that the habit-loop sits in a specific part of the brain called basal ganglia, which is not so concerned with cognitive decision making or memorising — we might lose our memory, but not our habits).</p><p>While breaking the habit loop can aid to abandon an undesirable habit, establishment of a loop is important to form an intended habit. To establish the loop, we need to precede the response with an easily available and regular stimulus and arrange a reward post completion of the response. As an example, a regular early morning running habit can be developed by placing the running outfit such that it is the first thing we see after waking up (the stimulus) and an enjoyable breakfast after completing the run (as a reward).</p><p><strong>Our habits are shaped by our environment</strong></p><p>Three groups of people influence our habits the most:</p><ol><li>The ones who are close to us by sharing the same living or workspace. We see them day after day and start emulating some of their practices. It will be easier to pick a habit which is similar to the habits our close ones have.</li><li>The many — the people who form the part of the immediate society that we belong to. We subconsciously emulate them because we believe that will make us feel more included. Workout communities are heavily based on this idea and have become popular during the last decade. The members of the community also push each other to help the habit develop.</li><li>The powerful — the successful people whom we admire and want to be like.</li></ol><p><strong>The Goldilocks rule — to make habits stick</strong></p><blockquote>The Goldilocks Rule states that humans experience peak motivation when working on tasks that are right on the edge of their current abilities. Not too hard. Not too easy.</blockquote><p>Habit is formed only by repetitions of certain activity such that it develops into an automated activity in our brain. The brain craves for novelty and any kind of repetitive task is immensely boring and demotivating. We love challenges and doing something repeatedly which we have already mastered is the least exciting. However, something too difficult is also immensely taxing for our brain which does not take repeated failures sportingly. The trick is to crank up the difficultly of our repeated task only slightly so that it still challenges us but within our limits.</p><p><strong>Conclusion</strong></p><p>Habit formation is much more than just discipline, we need to understand how the brain develops habits to devise an effective strategy and then be disciplined to stick to it. However, it is worth putting in the effort to plan and develop a habit because tiny gains they fetch us everyday compounds overtime to give us the coveted returns.</p><p><em>References:</em></p><ol><li><a href="https://www.amazon.com/Atomic-Habits-Proven-Build-Break/dp/0735211299"><em>https://www.amazon.com/Atomic-Habits-Proven-Build-Break/dp/0735211299</em></a></li><li><a href="https://gdt.stanford.edu/the-habit-loop/"><em>https://gdt.stanford.edu/the-habit-loop/</em></a></li><li><a href="https://www.amazon.com/Power-Habit-What-Life-Business/dp/081298160X"><em>https://www.amazon.com/Power-Habit-What-Life-Business/dp/081298160X</em></a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7d004dbbd8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>