<?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 Seulgie Han on Medium]]></title>
        <description><![CDATA[Stories by Seulgie Han on Medium]]></description>
        <link>https://medium.com/@su-paris?source=rss-6259b032bb9a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WFk49vor_5JjPyClieEnMw.jpeg</url>
            <title>Stories by Seulgie Han on Medium</title>
            <link>https://medium.com/@su-paris?source=rss-6259b032bb9a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 18:19:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@su-paris/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[Open-Source Contribution: A Warnings Bug in MovingPandas]]></title>
            <link>https://medium.com/@su-paris/open-source-contribution-a-warnings-bug-in-movingpandas-47713066b6fb?source=rss-6259b032bb9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/47713066b6fb</guid>
            <category><![CDATA[geospatial-data]]></category>
            <category><![CDATA[movingpandas]]></category>
            <category><![CDATA[open-source-contribution]]></category>
            <dc:creator><![CDATA[Seulgie Han]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 12:33:06 GMT</pubDate>
            <atom:updated>2026-09-14T12:33:06.721Z</atom:updated>
            <content:encoded><![CDATA[<p>How reading one small decorator taught me more about Python’s warnings module than years of using it.</p><p>After a stretch away from hands-on coding, I wanted to get back into the codebases I care about — geospatial and mobility data. So I picked an open-source library, opened it up, and started reading. This is the story of the first bug I found and fixed, written partly to share it and partly to cement what I re-learned along the way.</p><h3>What is MovingPandas?</h3><p><a href="https://github.com/movingpandas/movingpandas">MovingPandas</a> is a Python library for movement data — GPS tracks, vehicle trajectories, animal migration paths, anything that moves through space over time.</p><p>If you’ve used GeoPandas, the mental model is familiar. GeoPandas gives you a GeoDataFrame where each row has a geometry (a point, a line, a polygon). MovingPandas builds one layer up: it introduces a Trajectory object — a time-ordered sequence of positions for a single moving entity — and a TrajectoryCollection for many of them at once. On top of that it gives you the operations you actually need for movement analysis: stop detection, trajectory smoothing and cleaning, generalization, splitting, and aggregation into flows and clusters.</p><p>It’s built on top of Pandas, GeoPandas, and the Holo Viz plotting ecosystem, and it’s maintained largely by Anita Graser, a well-known figure in the open-source geospatial world.</p><h3>Why I chose it</h3><p><strong>It maps directly onto work I’ve done. </strong>Earlier in my career I built a GPS-trajectory anomaly-detection system for a construction fleet — reconstructing trips from raw telemetry, detecting stops, mapping points to zones, scoring unusual behavior. Back then I wrote much of that by hand. MovingPandas is, in a sense, the library version of everything I once hand-rolled. Reading its source is the fastest way for me to re-warm that domain sense and see how the ecosystem solved the same problems.</p><p><strong>Small, focused libraries are welcoming.</strong> A giant framework has a steep on-ramp and a crowded issue tracker. A focused, actively maintained library like MovingPandas has a smaller surface area, and enough rough edges that a careful reader can find something real to fix. For a first contribution, that’s ideal.</p><p>So I set up a development evnrionment, ran the full test suite (423 tests, all passing), and started reading. The test run itself gave me my first lead: a wall of DeprecationWaring messages scrolling past.</p><h3>The bug</h3><p>I followed one of those warnings to its source and found this decorator in movingpandas/tools/_warnings.py:</p><pre>import warnings<br>import functools<br><br><br>def deprecated(func):<br>    &quot;&quot;&quot;This is a decorator which can be used to mark functions<br>    as deprecated. It will result in a warning being emitted<br>    when the function is used.&quot;&quot;&quot;<br><br>    @functools.wraps(func)<br>    def new_func(*args, **kwargs):<br>        warnings.simplefilter(&quot;always&quot;, DeprecationWarning)  # turn off filter<br>        warnings.warn(<br>            &quot;Call to deprecated function {}.&quot;.format(func.__name__),<br>            category=DeprecationWarning,<br>            stacklevel=2,<br>        )<br>        warnings.simplefilter(&quot;default&quot;, DeprecationWarning)  # reset filter<br>        return func(*args, **kwargs)<br><br>    return new_func</pre><p>The intent is fine: mark a function as deprecated so that calling it emits a DeprecationWarning. The problem is the two simplefilter lines wrapped around the warn call.</p><p>To see why that’s a problem, it helps to recall how Python’s warnings module actually works.</p><h3><strong>A quick refresher on Python </strong><strong>warnings</strong></h3><p>Python keeps a <strong>global list of warning filters. </strong>Each filter decides what happens when a warning of a given category is raised — show it, show it once, ignore it, raise it as an error. This list is process-wide: it lives in warnings.filters and it’s shared by every module and every library running in that process.</p><ul><li>warnings.warn(...) raises a warning. It consults the current filters to decide what to do with it.</li><li>warnings.simplefilter(action, category) mutates that global filter list — it inserts a new rule at the front for everybody.</li></ul><p>That distiction is the whole bug. warn is a local action: it emits one warning and respects whatever configuration the user has chosen. simplefilter is a global action: it changes the rules for the entire program.</p><h3>Why the decorator’s version is harmful</h3><p>Now look again at what the decorator does on every single call to a deprecated function:</p><ol><li>simplefilter(&quot;always&quot;, ...) — overwrite the global filter so this warning always shows.</li><li>warn(...) — emit the warning.</li><li>simplefilter(&quot;default&quot;, ...) — overwrite the global filter again, this time to “default”.</li></ol><p>There are two things wrong here.</p><p><strong>It stomps on the user’s configuration.</strong> Suppose I’m using MovingPandas insde a larger application and I’ve deliberately silenced deprecation warnings:</p><pre>import warnings<br>warnings.simplefilter(&quot;ignore&quot;)   # I don&#39;t want to see these right now</pre><p>The moment any deprecated MovingPandas function runs, my setting is gone — overwritten first by &quot;always&quot;, then by &quot;default.&quot;. I nver asked for that.</p><p><strong>The “reset” doesn’t actually restore anything. </strong>The comment says #reset filter, but simplefilter(&quot;default&quot;, ...) doesn’t remember and restore my previous state. It just forces Python’s default. If I had configured something custom, it’s lost either way.</p><p>This is a known anti-pattern, and Python’s own documentation is explicit about it: library code should generally not insert filters, because doing so changes the behavior of every application that imports the library. Emitting the warning with warn() alone is enough — and then each user’s own configuration decides what happens to it, which is exactly how it should be.</p><h3>The fix</h3><p>The fix is to delete the two simplefilter lines and keep only the warn call:</p><pre>def deprecated(func):<br>    &quot;&quot;&quot;This is a decorator which can be used to mark functions<br>    as deprecated. It will result in a warning being emitted<br>    when the function is used.&quot;&quot;&quot;<br><br>    @functools.wraps(func)<br>    def new_func(*args, **kwargs):<br>        warnings.warn(<br>            &quot;Call to deprecated function {}.&quot;.format(func.__name__),<br>            category=DeprecationWarning,<br>            stacklevel=2,<br>        )<br>        return func(*args, **kwargs)<br><br>    return new_func</pre><p>Two lines gone, nothing else touched. The warning is still emitted; the global state is left alone.</p><p>One detail worth keeping: stacklevel=2. Without it, the warning points at the line<em> inside</em> the decorator, which is useless to a user. With stacklevel=2, Python reports the warning as coming from the<em> caller’s</em> line — the place that actually called the deprecated function. Small parameter, big difference in how usable the warning is.</p><h3>Proving it with tests</h3><p>A fix like this is easy to argue for in words, but a pull request is stronger when it proves the claim in code. So I added a small test file. The key idea: use a throwaway function decorated with @deprecated , so I’m testing the decorator itself and not some unrelated warning from a real library function.</p><pre>import warnings<br>import pytest<br>from movingpandas.tools._warnings import deprecated<br><br><br>@deprecated<br>def _deprecated_example():<br>    &quot;&quot;&quot;A deprecated function used only for testing the decorator.&quot;&quot;&quot;<br>    return 42<br><br><br>def test_deprecated_still_emits_warning():<br>    with pytest.warns(DeprecationWarning, match=&quot;deprecated function&quot;):<br>        result = _deprecated_example()<br>    assert result == 42<br><br><br>def test_deprecated_does_not_mutate_global_filter():<br>    with warnings.catch_warnings():<br>        warnings.resetwarnings()<br>        warnings.simplefilter(&quot;ignore&quot;)<br>        filters_before = list(warnings.filters)<br><br>        _deprecated_example()<br><br>        assert warnings.filters == filters_before</pre><ul><li>pytest.warns(...) asserts that the block raises the expected warning. The first test uses it to confirm the fix didn’t accidently silence the deprecation — the warning must still fire, and the wrapped function must still return its value.</li><li>warnings.catch_warnings() is a context manager that snapshots the filter state on entry and restores it on exit. It means the test can freely configure filters without leaking that configuration into other tests. Inside it, the second test sets a filter, calls the deprecated function, and asserts the filter list is unchanged. Against the old code this test fails, because simplefilter mutated the list. Against the fix, it passes.</li></ul><p>That second test is the whole bug report, expressed as an executable assertion.</p><h3>What I took away</h3><p>The change is tiny — two deleted lines and a short test file. But the value wasn’t the size of the diff. It was the process, and it’s a process worth repeating:</p><ul><li><strong>Read the source, don’t just guess.</strong> The warning was a symptom; the decorator was the cause. Finding it meant actually opening the file.</li><li><strong>Understand before you change.</strong> I re-learned the real distinction between warn (local, respectful) and simplefilter (global, invasive) — the kind of thing you use for years without ever examining.</li><li><strong>Keep the change minimal.</strong> Remove exactly what’s wrong.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CbrhxKkDlF-eFdk4jrjwqQ.png" /></figure><p>If you’ve been meaning to make a first open-source contribution and it feels intimidating, my suggestion is this: pick a library you already have some feel for, set it up, run its tests, and just start reading.</p><p><em>Next up, I’m continuing in the geospatial and mobility space — more trajectory work, and eventually contributions closer to the movement-analysis core of the library.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47713066b6fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ Memory Management — MemBot Project (Part3: Final Submission & Reflection)]]></title>
            <link>https://medium.com/@su-paris/c-memory-management-membot-project-part3-final-submission-reflection-ff7aab22c39a?source=rss-6259b032bb9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff7aab22c39a</guid>
            <category><![CDATA[move-semantics]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[c-plus-plus-programming]]></category>
            <category><![CDATA[smart-pointer]]></category>
            <dc:creator><![CDATA[Seulgie Han]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 13:06:33 GMT</pubDate>
            <atom:updated>2026-04-24T13:54:39.745Z</atom:updated>
            <content:encoded><![CDATA[<p>After Part 1 and Part 2, the MemBot project was no longer just a chatbot implementation. It became a full exercise in understanding <strong>ownership, move semantics, and real C++ lifetime management under a graph structure.</strong></p><p><a href="https://medium.com/@su-paris/understanding-the-membot-project-ddfdad7affab">Memory Management ChatBot Part1</a></p><p><a href="https://medium.com/@su-paris/understanding-the-membot-project-ownership-move-semantics-and-graph-design-8dcc259c657d">Memory Management ChatBot Part2</a></p><p>This final post summarizes what changed during implementation, what broke along the way, and what ultimately made the project pass all rubric requirements.</p><h3>From Confusion to Working System</h3><p>At the beginning, the project looked simple:</p><ul><li>Load a graph</li><li>Match keywords</li><li>Move between nodes</li><li>Print responses</li></ul><p>But the real complexity came from one hidden requirement:</p><blockquote>Every object must have a clearly defined ownership model at all times.</blockquote><p>Once this rule was violated, the program would immediately show symptoms like:</p><ul><li>segmentation faults (segfault)</li><li>double destruction</li><li>null pointer dereferencing</li><li>silent logic failure</li></ul><p>Most debugging effort was not about chatbot logic — but about <strong>who owns what in memory.</strong></p><h3>Final Ownership Model (What Actually Worked)</h3><p>After multiple iterations, the final working architecture looked like this:</p><p><strong>ChatLogic (Graph Owner)</strong></p><ul><li>Owns all GraphNode objects via std::vector&lt;std::unique_ptr&lt;GraphNode&gt;&gt;</li><li>Responsible for loading and constructing the graph</li><li>Does NOT own ChatBot</li></ul><pre>std::vector&lt;std::unique_ptr&lt;GraphNode&gt;&gt; _nodes:<br>GraphNode* _currentNode; // non-owning<br>ChatBot* _chatBot; // non-owning</pre><p><strong>GraphNode (Edge Owner)</strong></p><p>Each node:</p><ul><li>Owns its outgoing edges using std::vector&lt;std::unique_ptr&lt;GraphEdge&gt;&gt;</li><li>Keeps raw pointers for parent relationships (non-owning back references)</li><li>Temporarily interacts with ChatBot but does not own it</li></ul><pre>std::vector&lt;std::unique_ptr&lt;GraphEdge&gt;&gt; _childEdges;<br>std::vector&lt;GraphEdge*&gt; _parentEdges;<br>ChatBot* _chatBot; // non-owning</pre><p><strong>GraphEdge (Pure Connector)</strong></p><p>Edges are lightweight transition objects:</p><ul><li>Do NOT own nodes</li><li>Only store raw pointers to parent/child nodes</li><li>Store keywords for matching logic</li></ul><pre>GraphNode* _parentNode; // non-owning<br>GraphNode* _childNode; // non-owning<br>std::vector&lt;std::string&gt; _keywords;</pre><p>ChatBot (Traveler Object)</p><p>ChatBot is the most intersting part.</p><ul><li>It does NOT own the graph</li><li>It does NOT own ChatLogic</li><li>It moves between nodes using move semantics</li></ul><pre>GraphNode* _currentNode; // non-owning<br>GraphNode* _rootNode; // non-owning<br>ChatLogic* _chatLogic; // non-owning</pre><p>Its job is only:</p><blockquote>Carry state and move through the graph safely</blockquote><h3>The Critical Fix That Solved Everything</h3><p>The final major issue was not compilation — it was runtime crash.</p><p>The root cause:</p><blockquote>_chatLogic was never properly connected or was treated as ownership incorrectly.</blockquote><p>This caused:</p><ul><li>null pointer dereference when sending messages</li><li>ChatBot calling methods on invalid state</li></ul><h4>Final Decision</h4><p>Two possible designs were evaluated:</p><p><strong>Option A (correct for CLI version)</strong></p><ul><li>ChatLogic is stack-allocated in main</li><li>ChatBot holds a<strong> non-owning pointer</strong></li><li>No unique_ptr ownership transfer</li></ul><p><strong>Option B (full ownership model)</strong></p><ul><li>ChatLogic is heap-allocated via std::unique_ptr</li><li>ChatBot receives pointer via .get()</li></ul><h4>Final implemented solution:</h4><p><strong>Option A (clean CLI adaption)</strong> Because:</p><ul><li>CLI main already owns ChatLogic</li><li>Graph already demonstrates unique_ptr ownership elsewhere</li><li>No need to artificially heap-allocate everything</li></ul><h3>Why Move Semantics were Still Required</h3><p>Even though ChatLogic is simple in CLI version, the <strong>ChatBot still uses move semantics heavily. </strong>This is because:</p><ul><li>ChatBot must transfer state between nodes</li><li>Only one active ChatBot exists at a time</li><li>Copying would create duplicate active agents (invalid design)</li></ul><p>So this pattern remained critical:</p><pre>newNode-&gt;moveChatbotHere(std::move(_chatBot));</pre><p>After move:</p><ul><li>Old node -&gt; _chatBot == nullptr</li><li>New node -&gt; owns active chatbot state (temporarily)</li></ul><p>This guarantees:</p><blockquote>Only one valid ChatBot exists in the system at any time.</blockquote><h3>What Finally Passed the Rubric</h3><ol><li><strong>Smart Pointer Ownership</strong></li></ol><ul><li>GraphNode ownership converted to std::unique_ptr</li><li>GraphEdge ownership converted to std::unique_ptr</li><li>No manual delete anywhere in graph</li></ul><p><strong>2. Rule of Five (ChatBot)</strong></p><ul><li>Implemented fully</li><li>Move constructor active</li><li>Move assignment active</li><li>Copy operations controlled</li><li>Debug prints confirm execution path</li></ul><p><strong>3. No Circular Ownership</strong></p><ul><li>Nodes do not own nodes</li><li>Edges do not own nodes</li><li>ChatBot does not own graph</li><li>ChatLogic does not own ChatBot</li></ul><p><strong>4. Runtime Stability</strong></p><ul><li>No segmentation faults</li><li>No double deletion</li><li>Clean lifecycle logs</li><li>Stable CLI interaction loop</li></ul><h3>Final Mental Model (What This Project Really Teaches)</h3><p>The most important takeaway is not syntax. It is this:</p><blockquote>C++ is not about writing code- it is about defining ownership boundaries.</blockquote><p>Before writing any structure, you must be able to answer:</p><ul><li>Who owns this project?</li><li>Who deletes it?</li><li>Who only observes it?</li><li>Can it move safely?</li><li>Can it ever be copied safely?</li></ul><p>If these answers are unclear, the program will eventually break — even if it compiles!</p><h3>Final Reflection</h3><p>MemBot started as a chatbot project, but ended as a <strong>memory architecture design exercise.</strong> The hardest part was not implementing features, but:</p><ul><li>removing accidental ownership</li><li>replacing new ownership with unique_ptr</li><li>enforcing move semantics instead of copying</li><li>debugging crashes casued purely by lifetime mistakes</li></ul><p>In the end, the system became simple:</p><blockquote>One owner per object. Everyone else observes. ChatBot moves, but never duplicates.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTlb2Fi5s_lTnpkIeI_Ndg.png" /></figure><h3>Series Conclusion</h3><ul><li>Part 1: Understanding structure</li><li>Part 2: Understanding ownership</li><li>Part 3: Making it actually work safely</li></ul><p>At this point, the MemBot project is a controlled memory system disguised as a chatbot :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff7aab22c39a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Threads in C++]]></title>
            <link>https://medium.com/@su-paris/understanding-threads-in-c-ccee82cc87fb?source=rss-6259b032bb9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccee82cc87fb</guid>
            <category><![CDATA[concurrent-programming]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Seulgie Han]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 09:14:42 GMT</pubDate>
            <atom:updated>2026-01-22T09:14:42.150Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern applications must do multiple things at once: handle user input, fetch data, render UI, and process background tasks. To achieve this efficiently, we rely on <strong>concurrency</strong>, and in C++ that usually means <strong>threads</strong>. This post walks step-by-step through:</p><ul><li>Processes vs Threads</li><li>Creating threads in C++</li><li>join() vs detach()</li><li>Passing data to threads safely</li><li>Understanding std::promise and std::future with a concrete example</li></ul><h3>Processes vs Threads (Restaurant Analogy)</h3><p>Think of <strong>processes</strong> as <strong>separate restaurants.</strong></p><ul><li>Each restaurant has its own kitchen, staff, and inventory</li><li>One restaurant cannot directly access another restaurant’s kitchen</li><li>Communication requires phone calls, emails, or delivery trucks (IPC)</li><li>This is <strong>safe</strong>, but slow and expensive</li></ul><p>Benefit:</p><p>If one restaurant burns down, the others keep running. That’s why browsers often use <strong>one process per tab</strong>.</p><p>Now think of <strong>threads</strong> as <strong>kitchen staff inside the same restaurant</strong>.</p><ul><li>They share the same kitchen</li><li>They share ingredients</li><li>They share tools and workspace</li></ul><p>This makes communication <strong>very fast,</strong> but introduces new problems.</p><blockquote>What happens if two cooks grab the same pan at the same time?</blockquote><p>That’s the core trade-off:</p><ul><li><strong>Processes -&gt; safety through isolation</strong></li><li><strong>Threads -&gt; performance through sharing</strong></li></ul><h3>Creating Threads in C++</h3><p><strong>Basic Thread Creation</strong></p><pre>#include &lt;thread&gt;<br>#include &lt;iostream&gt;<br><br>void prep_vegetables() {<br>    std::cout &lt;&lt; &quot;Chopping vegetables&quot; &lt;&lt; std::endl;<br>}<br><br>int main() {<br>    std::thread prep_cook(prep_vegetables);<br>    prep_cook.join();<br>}</pre><p>A thread is simply: “Run this function on another execution path”</p><p>Calling join() means: “Wait until this worker finishes before continuing”</p><p><strong>Lambda-Based Threads</strong></p><pre>std::thread grill_cook([]() {<br>    std::cout &lt;&lt; &quot;Grilling steaks&quot; &lt;&lt; std::endl;<br>});<br>grill_cook.join();</pre><p>Lambdas are useful for short, one-off tasks without defining a separate function.</p><h4>What Happens Without Proper Management?</h4><p>The code below has multiple threads but never joined or detached. As a result, output appears mixed and unpredictable and program crashes with terminate called without an active exception. Because <strong>C++ requires every thread to be either joined or detached </strong>before its destructor runs. This is not optional.</p><pre>std::thread t1(thread_function, 1);<br>std::thread t2(thread_function, 2);<br>std::thread t3(thread_function, 3);<br>std::thread t4([]() {<br>    std::cout &lt;&lt; &quot;Hello from a lambda thread!&quot; &lt;&lt; std::endl;<br>});<br><br>std::cout &lt;&lt; &quot;&gt;&gt;&gt; Main thread ending&quot; &lt;&lt; std::endl;</pre><h4>Join vs Detach</h4><p>Thread lifecycle management determines whether:</p><ul><li>the main thread <strong>waits</strong></li><li>or lets the worker <strong>run independently</strong></li></ul><h4>join() — “Don’t leave until the job is done”</h4><pre>std::thread prep_cook(prepare_mise_en_place);<br>prep_cook.join();</pre><p>Use join() when later code depends on the result, correctness matters and when you need confirmation the task finished. This is <strong>synchronous coordination</strong>.</p><h4>detach() — “Work independently” (Background Work)</h4><pre>void detached_thread_function() {<br>    int counter = 1;<br>    while (true) {<br>        std::cout &lt;&lt; &quot;Detached thread is working... &quot;<br>                  &lt;&lt; counter++ &lt;&lt; std::endl;<br>        std::this_thread::sleep_for(std::chrono::milliseconds(500));<br>    }<br>}<br><br>std::thread t4(detached_thread_function);<br>t4.detach();</pre><p>This thread runs independently, and continues while main() is alive. It stops automatically when the program exits. Use detach() when the task runs in the background, results are not needed and when it’s truly fire-and-forget. This is<strong> asynchronous execution</strong>.</p><blockquote>Every thread must be either joined or detached before destruction.</blockquote><h3>Passing Objects to Threads</h3><h4>Pass by Value — Safest Default</h4><pre>void cook_pasta(std::vector&lt;std::string&gt; ingredients) {<br>    ingredients.push_back(&quot;parmesan&quot;);<br>}<br><br>std::vector&lt;std::string&gt; pantry = {&quot;pasta&quot;, &quot;tomatoes&quot;};<br>std::thread t(cook_pasta, pantry);<br>t.join();</pre><p>Each thread gets its own copy. No race conditions. No lifetime issues.</p><h4>Pass by Reference — Shared State</h4><pre>void update_inventory(std::atomic&lt;int&gt;&amp; count) {<br>    count.fetch_add(-2);<br>}<br><br>std::atomic&lt;int&gt; tomato_count{50};<br>std::thread t(update_inventory, std::ref(tomato_count));<br>t.join();</pre><p>Shared access requires atomics, mutexes and strict lifetime guarantees.</p><h4>Dangerous Pattern: Referencing Local Data</h4><pre>void dangerous_example() {<br>    std::vector&lt;std::string&gt; local_items = {&quot;flour&quot;, &quot;eggs&quot;};<br><br>    std::thread baker([&amp;local_items]() {<br>        std::this_thread::sleep_for(std::chrono::seconds(1));<br>        for (auto&amp; item : local_items) {<br>            std::cout &lt;&lt; item &lt;&lt; std::endl;<br>        }<br>    });<br><br>    baker.detach();<br>} // local_items destroyed → crash</pre><p>Detached threads + local references = <strong>undefined behavior</strong>.</p><h4>Promise &amp; Future: Returning Results from Threads</h4><p>Sometimes a thread must <strong>compute something and send the result back</strong>. This is where std::promise and std::future shine. What are they?</p><ul><li>std::promise&lt;T&gt; : a container to <strong>set a value</strong></li><li>std::future&lt;T&gt; : a handle to <strong>retrieve that value</strong></li></ul><p>If one thread produces, another thread consumes. Let’s see the real example : Daily Revenue Calculation</p><pre>#include &lt;future&gt;<br>#include &lt;thread&gt;<br>#include &lt;vector&gt;<br><br>struct Order {<br>    double amount;<br>};<br><br>void calculate_daily_revenue(<br>    const std::vector&lt;Order&gt;&amp; orders,<br>    std::promise&lt;double&gt; revenue_promise<br>) {<br>    double total = 0.0;<br>    for (const auto&amp; order : orders) {<br>        total += order.amount;<br>        std::this_thread::sleep_for(std::chrono::milliseconds(500));<br>    }<br>    revenue_promise.set_value(total);<br>}<br><br>int main() {<br>    std::vector&lt;Order&gt; orders = {{12.5}, {20.0}, {7.5}};<br><br>    std::promise&lt;double&gt; promise;<br>    std::future&lt;double&gt; future = promise.get_future();<br><br>    std::thread accountant(<br>        calculate_daily_revenue,<br>        orders,<br>        std::move(promise)<br>    );<br><br>    double revenue = future.get(); // waits automatically<br>    std::cout &lt;&lt; &quot;Today&#39;s revenue: $&quot; &lt;&lt; revenue &lt;&lt; std::endl;<br><br>    accountant.join();<br>}</pre><h4>What’s Happening Step by Step?</h4><ol><li>Main thread creates a <strong>promise</strong></li><li>Main thread gets a <strong>future </strong>connected to it</li><li>Worker thread calculates revenue</li><li>Worker calls set_value()</li><li>future.get() unblocks and receives the value</li></ol><p>No mutex. No shared memory. No race conditions.</p><p>When in doubt, pass by value. Use references only when shared state is necessary and safe. And remember that threads are easy to create. Correct thread management is what separates demos from production code.</p><h3>Final Takeaway</h3><p>Concurrency is powerful — but unforgiving.</p><ul><li>Always manage thread lifetimes</li><li>Be explicit with join() or detach()</li><li>Respect data ownership and lifetime</li><li>Use promise/future for clean result passing</li></ul><p>Solidifying these fundamentals makes modern, responsive C++ applications possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccee82cc87fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the MemBot Project — Ownership, Move Semantics, and Graph Design]]></title>
            <link>https://medium.com/@su-paris/understanding-the-membot-project-ownership-move-semantics-and-graph-design-8dcc259c657d?source=rss-6259b032bb9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dcc259c657d</guid>
            <dc:creator><![CDATA[Seulgie Han]]></dc:creator>
            <pubDate>Fri, 16 Jan 2026 22:59:38 GMT</pubDate>
            <atom:updated>2026-01-16T22:59:38.571Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding the MemBot Project — Ownership, Move Semantics, and Graph Design</h3><p>Udacity C++ Memory Management — Project Walkthrough (Part2)</p><p>In Part 1, we focused on <strong>what the project looks like</strong>. In Part 2, we focus on <strong>why it is designed this way</strong>. If you try to “just fill in the TODOs”, you will almost certainly:</p><ul><li>break ownership rules</li><li>leak memory</li><li>or accidentally copy objects that must be moved</li></ul><p>Let’s state the most important rule upfront:</p><blockquote><strong>At any point in time, every object must have exactly one clear owner.</strong></blockquote><p>This applies to:</p><ul><li>GraphNodes</li><li>GraphEdges</li><li>ChatBot</li></ul><p>Everything else uses <strong>non-owning raw pointers</strong>. Before touching code, we must clearly separate <strong>Ownership</strong> vs<strong> Access</strong>. Ownership means responsible for deleting the object, whereas Access means the availability to use the object / must NOT delete it. In this project:</p><ul><li>GraphNode is owned by ChatLogic</li><li>GraphEdge is owned by GraphNode (parent side)</li><li>ChatBot is owned by Moves between GraphNodes</li></ul><p>Everyone else only <strong>borrows pointers</strong>.</p><h3>Understanding ChatBot</h3><p>Understanding ChatBot ownership is crucial in this project. Ownership Structure:</p><ul><li><strong>The root GraphNode owns the ChatBot </strong>— Root Node creates and manages the ChatBot object</li><li><strong>ChatLogic does NOT own the ChatBot </strong>— it only holds a pointer (_chatBot) to interact with it. Just has a pointer; does not delete or manage</li><li><strong>Other GraphNodes only reference the ChatBot</strong> temporarily as it moves along the graph.</li></ul><h4>Why this design?</h4><ol><li><strong>There should always be only one ChatBot </strong>— no two nodes can own it at the same time.</li><li><strong>Move semantics</strong> allow the ChatBot to safely travel from one side to another.</li><li><strong>Clear ownership</strong> — <em>root node manages lifetime</em>, so no double deletion occurs.</li></ol><p>If ChatBot were copied instead of moved, two nodes could think they own the chatbot, and both would try to talk and control state. This violates single responsiblity and single ownership. Move semantics guarantee:</p><blockquote>After moving, the source object is empty and safe.</blockquote><h4>How It Works in Code</h4><pre>// Root node creates ChatBot<br>ChatBot chatBot(&quot;../images/chatbot.png&quot;); <br>_chatBot-&gt;SetRootNode(rootNode);<br><br>// Moving the ChatBot to a new node<br>_currentNode-&gt;MoveChatbotToNewNode(newNode);</pre><ul><li>MoveChatbotToNewNode uses std::move(_chatbot)</li><li>Previous node _chatBot becomes nullptr</li><li>New node temporaily <strong>references</strong> the ChatBot but does not own it</li></ul><h4>ChatBot Movement Flow (Step-by-Step)</h4><p>Let’s trace a typical user interaction.</p><p>Step 1: User sends a message</p><pre>ChatLogic::SendMessageToChatBot(&quot;What is a pointer?&quot;);</pre><p>Step 2: ChatBot processes input</p><pre>ChatBot::ReceiveMessageFromUser(...)</pre><p>Step 3: Current node transfers ChatBot</p><pre>_currentNode-&gt;MoveChatbotToNewNode(newNode);</pre><p>Step 4: Ownership transfer happens</p><pre>newNode-&gt;moveChatbotHere(std::move(_chatBot));</pre><p>std::move does NOT move by itself. It enables the <strong>move constructor.</strong></p><h4>Why Rule of Five Is Tested Here</h4><p>ChatBot implements:</p><pre>ChatBot(ChatBot &amp;&amp;source);<br>ChatBot &amp;operator=(ChatBot &amp;&amp;source);</pre><p>These functions transfer internal pointers, reset the source object, and avoid double references. The printed log messages exist so you can <strong>verify moves happen</strong>.</p><h4>The ChatBot Does Not Own ChatLogic</h4><p>This is subtle but crucial.</p><pre>_chatLogic-&gt;SetChatbotHandle(this);</pre><p>This creates a <strong>two-way connection</strong>. ChatBot knows ChatLogic and ChatLogic knows ChatBot. But neither owns the other. Why is this safe? Because both objects live for the duration of the program, and lifetime is controlled externally (main).</p><p>The main_cli.cpp is simple. As the CLI entry point, it only creates ChatLogic, load graph, and start loop. This is intentional. Memory complexity belongs inside the graph, not in main.</p><p>In GraphNode:</p><pre>std::vector&lt;GraphEdge*&gt; _parentEdges;</pre><p>This vector does NOT delete edges, only exists to answer questions like “How many parents does this node have?” — If child nodes owned incoming edges, that will lead to <strong>double deletion</strong>.</p><h4>Key Takeaways</h4><ul><li><strong>Owner</strong>: Root Node</li><li><strong>References</strong>: ChatLogic and all other GraphNodes</li><li><strong>Behavior</strong>: Only one ChatBot exists at a time, moving safely along the graph</li></ul><h4>Avoid to:</h4><ul><li>use shared_ptr everywhere</li><li>Copy ChatBot instead of moving</li><li>Let both nodes own the same edge</li><li>Delete objects manaually “just in case”</li></ul><h4>Before touching any TODO, answer these questions:</h4><ol><li>Who owns this object?</li><li>Who deletes it?</li><li>Can it be copied safely?</li><li>Should it be moved instead?</li><li>Is this pointer owning or non-owning?</li></ol><h3>Final Ownership Diagram (Target Design)</h3><pre>ChatLogic<br> ├── owns → GraphNode<br> │           ├── owns → GraphEdge<br> │           │          └── points to → GraphNode<br> │           └── non-owning ← GraphEdge<br> └── references → ChatBot<br><br>ChatBot<br> ├── currentNode (non-owning)<br> ├── rootNode (non-owning)<br> └── chatLogic (non-owning)</pre><p>Single ownership everywhere. Zero ambiguity.</p><p>In the next post, we will finally:</p><ul><li>Fill in <strong>all TODOs</strong></li><li>Convert ownership to unique_ptr where required</li><li>Implement safe move logic</li><li>Validate against the project rubric</li></ul><p>At that point, this project stops being “confusing” and becomes mechanically logical.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dcc259c657d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the MemBot Project]]></title>
            <link>https://medium.com/@su-paris/understanding-the-membot-project-ddfdad7affab?source=rss-6259b032bb9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddfdad7affab</guid>
            <category><![CDATA[c-plus-plus-language]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[chatbot-design]]></category>
            <dc:creator><![CDATA[Seulgie Han]]></dc:creator>
            <pubDate>Thu, 15 Jan 2026 17:31:48 GMT</pubDate>
            <atom:updated>2026-01-15T17:31:48.065Z</atom:updated>
            <content:encoded><![CDATA[<p>Udacity C++ Memory Management — Project Walkthrough (Part 1)</p><p>MemBot project is part of Udacity’s C++ Memory Management course. At first glance, it looks like a chatbot project. But in reality, this is not an AI project. This project is about <strong>memory ownership, object lifetime, and move semantics in C++.</strong></p><p>The chatbot logic itself is <strong>already implemented</strong> in the project template. The real job is to:</p><ul><li>Understand <strong>who owns what</strong></li><li>Decide <strong>where memory should live</strong></li><li>Make sure objects are <strong>moved, not copied</strong></li><li>Prevent <strong>memory leaks and double deletes</strong></li></ul><p>I’m writing this post as a study recap, because you cannot safely write modern C++ unless you fully understand the existing structure.</p><h3>High-Level Concept: What is MemBot?</h3><p>MemBot works by navigating a <strong>knowledge graph</strong>.</p><p><strong>Core idea</strong></p><ul><li>Each <strong>GraphNode</strong> contains chatbot answers</li><li>Each <strong>GraphEdge</strong> represents a transition between answers</li><li>The <strong>ChatBot</strong> moves from node to node based on user input</li></ul><p>Think of like this:</p><pre>User Input<br>   ↓<br>ChatBot<br>   ↓<br>GraphNode (current answer)<br>   ↓<br>GraphEdge (matched by keyword)<br>   ↓<br>Next GraphNode</pre><p>This design allows us to practice <strong>pointer ownership and move semantics</strong> in a realistic object graph.</p><h3>Project Structure Overview</h3><p>Here are the most important source files:</p><pre>src/<br>├── chatbot.cpp / chatbot.h<br>├── chatlogic.cpp / chatlogic.h<br>├── graphnode.cpp / graphnode.h<br>├── graphedge.cpp / graphedge.h<br>└── main_cli.cpp</pre><p>Let’s quickly define responsibilities before diving deeper.</p><ul><li><strong>ChatBot</strong>: Represents the chatbot agent</li><li><strong>ChatLogic</strong>: Loads graph, manages overall flow</li><li><strong>GraphNode</strong>: Stores answers and edges</li><li><strong>GraphEdge</strong>: Connects nodes using keywords</li><li><strong>main_cli</strong>: Starts terminal interaction</li></ul><h3>The Knowledge Graph (Big Picture)</h3><p>The chatbot’s “brain” is stored in <strong>a text file</strong>, which looks like this:</p><pre>&lt;TYPE:NODE&gt;&lt;ID:0&gt;&lt;ANSWER:Hello, my name is MemBot&gt;<br>&lt;TYPE:NODE&gt;&lt;ID:1&gt;&lt;ANSWER:Let’s talk about memory&gt;<br>&lt;TYPE:EDGE&gt;&lt;ID:0&gt;&lt;PARENT:0&gt;&lt;CHILD:1&gt;&lt;KEYWORD:memory&gt;</pre><p>This gets converted into <strong>a graph in memory</strong>:</p><pre>+---------+      Edge (keyword: memory)      +---------+<br>| Node 0  | ------------------------------&gt; | Node 1  |<br>| Answer  |                                  | Answer  |<br>+---------+                                  +---------+</pre><p>Nodes do not own each other, edges connect nodes, and ownership flows downward. This is crucial later when we apply smart pointers.</p><h3>ChatBot Class — The “Traveler”</h3><p>ChatBot receives messages from the user, asks ChatLogic to send responses and moves between nodes using <strong>move semantics. </strong>It does not own the graph, delete nodes, or create edges. That is, ChatBot <strong>does not own</strong> anything here. It only <strong>points to existing objects</strong>. This avoids circular ownership and keeps lifetimes simple.</p><pre>class ChatBot {<br>private:<br>    GraphNode *_currentNode; // not owned<br>    GraphNode *_rootNode;    // not owned<br>    ChatLogic *_chatLogic;   // not owned<br>};</pre><h3>Rule of Five (Why It Matters Here)</h3><p>The ChatBot class implements the Rule of Five:</p><ol><li>Destructor</li><li>Copy constructor</li><li>Copy assignment</li><li>Move constructor</li><li>Move assignment</li></ol><p>Each function prints a message like:</p><pre>&gt;&gt;&gt; Rule of Five Component: ChatBot Move Constructor &lt;&lt;&lt;</pre><p>Why is this useful?</p><p>Because later, when the ChatBot moves between nodes, you can visually confirm:</p><ul><li>Was it copied? -&gt; Copying would be dangerous</li><li>Or was it moved? -&gt; Moving is safe and intended</li></ul><h3>ChatLogic — The Graph Manager</h3><p>ChatLogic is the <strong>central controller</strong>. What ChatLogic does?</p><ul><li>Reads the file</li><li>Creates all nodes and edges</li><li>Identifies the root node</li><li>Connects the ChatBot to the graph</li><li>Sends messages between ChatBot and UI</li></ul><pre>class ChatLogic {<br>private:<br>    std::vector&lt;GraphNode *&gt; _nodes; // owns nodes<br>    GraphNode *_currentNode;         // not owned<br>    ChatBot *_chatBot;               // not owned<br>};</pre><p><strong>Ownership rule</strong></p><ul><li>ChatLogic <strong>owns all GraphNodes</strong></li><li>ChatLogic <strong>does NOT own ChatBot</strong></li><li>ChatLogic <strong>does NOT own edges directly</strong> (this changes later)</li></ul><p>This design prevents double deletion and centralizes graph creation.</p><h3>GraphNode— The Answer Holder</h3><p>Each GraphNode contains:</p><ul><li>A list of answers</li><li>Edges to parent nodes (incoming)</li><li>Edges to child nodes (outgoing)</li><li>Possibly the ChatBot (temporarily)</li></ul><pre>class GraphNode {<br>private:<br>    std::vector&lt;GraphEdge*&gt; _childEdges;  // outgoing<br>    std::vector&lt;GraphEdge*&gt; _parentEdges; // incoming<br>    ChatBot *_chatBot;                    // not owned<br>};</pre><p>Why this structure?</p><ul><li>Nodes must <strong>know where they can go next</strong></li><li>Nodes must <strong>know who can lead to them</strong></li><li>Only <strong>one node at a time</strong> holds the ChatBot</li></ul><p>Later, this class will enforce <strong>exclusive ownership of outgoing edges</strong>.</p><h3>GraphEdge — The Connector</h3><p>GraphEdge represents <strong>possible transitions</strong>.</p><p>What an edge contains?</p><ul><li>Parent node (non-owning)</li><li>Child node (non-owning)</li><li>Keywords used for matching</li><li>Edge ID</li></ul><pre>class GraphEdge {<br>private:<br>    GraphNode *_parentNode; // not owned<br>    GraphNode *_childNode;  // not owned<br>    std::vector&lt;std::string&gt; _keywords;<br>};</pre><p>Edges <strong>do not own nodes</strong>. Nodes will eventually own edges. This avoids circular ownership like:</p><pre>Node owns Edge<br>Edge owns Node ❌ (bad)</pre><h3>Memory Ownership Map (So Far)</h3><p>Here’s the big picture.</p><pre>ChatLogic<br> ├── owns → GraphNode 0<br> │     ├── outgoing → GraphEdge 0<br> │     └── incoming ← none<br> ├── owns → GraphNode 1<br> │     ├── incoming ← GraphEdge 0<br> │     └── outgoing → ...<br> └── references → ChatBot</pre><p>ChatBot:</p><pre>ChatBot<br> ├── currentNode (pointer)<br> ├── rootNode (pointer)<br> └── chatLogic (pointer)</pre><p>No cycles. No ambiguity. Clean ownership.</p><h3>What we are NOT Required to Understand</h3><p>At this point, we do NOT need to deeply understand:</p><ul><li>Levenshtein distance implementation</li><li>Keyword matching logic</li><li>NLP-style decision making</li></ul><p>Those parts already work. The project is focused on <strong>memory correctness</strong>, not chatbot intelligence.</p><p>Instead, youshould understand:</p><ul><li>Why ownership matters</li><li>Why move semantics are required</li><li>Why raw pointers are still used in some places</li><li>Where smart pointers make sense</li></ul><p>If you don’t, you’ll end up with:</p><ul><li>Dangling pointers</li><li>Double deletes</li><li>Segmentation faults</li></ul><h3>In Part 2, we will:</h3><ul><li>Redesign ownership using unique_ptr</li><li>Explain <strong>incoming &amp; outgoing edge ownership</strong></li><li>Show how <strong>ChatBot moves between nodes</strong></li><li>Add <strong>move semantics diagrams</strong></li></ul><p>Once Part 2 is done, filling TODOs will feel not scary :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddfdad7affab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern C++ Memory Management: Smart Pointers]]></title>
            <link>https://medium.com/@su-paris/modern-c-memory-management-smart-pointers-7fd424ca5620?source=rss-6259b032bb9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fd424ca5620</guid>
            <category><![CDATA[c-plus-plus-programming]]></category>
            <category><![CDATA[smart-pointer]]></category>
            <category><![CDATA[shared-pointer]]></category>
            <category><![CDATA[weak-pointer]]></category>
            <dc:creator><![CDATA[Seulgie Han]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 22:41:46 GMT</pubDate>
            <atom:updated>2025-12-23T22:41:46.249Z</atom:updated>
            <content:encoded><![CDATA[<p>Memory management is one of the most challenging parts of learning C++. For beginners, raw pointers ( new / delete ) are often a source of bugs, crashes, and memory leaks.</p><p>Modern C++ solves most of these problems with <strong>smart pointers</strong>. This article explains <strong>why smart pointers exist</strong>, <strong>how they work</strong>, and <strong>when to use each one</strong>, with practical examples and refactoring patterns.</p><h3>Why Raw Pointers Are Dangerous</h3><p>Raw pointers do not express <strong>ownership.</strong></p><pre>int* ptr = new int(42);</pre><p>Questions immediately arise:</p><ul><li>Who is responsible for deleting this memory?</li><li>When should delete be called?</li><li>What happens if an exception occurs?</li></ul><p>If delete is forgotten -&gt; <strong>memory leak</strong></p><p>If delete is called twice -&gt;<strong> crash (double free)</strong></p><p>If ownership is unclear -&gt; <strong>undefined behavior</strong></p><p>Modern C++ avoids these problems by making <strong>ownership explicit.</strong></p><h3>RAII: The Foundation of Smart Pointers</h3><p>RAII (Resource Acquisition is Initialization) means:</p><blockquote>A resource is acquired during object construction and released automatically in the destructor.</blockquote><p>Smart pointers are RAII wrappers around raw pointers. When a smart pointer goes out of scope, its destructor <strong>automatically frees memory</strong>.</p><h4>std::unique_ptr — Exclusive Ownership</h4><p>What Is std::unique_ptr ?</p><pre>std::unique_ptr&lt;T&gt;</pre><ul><li>Exactly <strong>one owner</strong></li><li>Cannot be copied</li><li>Can only be <strong>moved</strong></li><li>Zero or near-zero runtime overhead</li></ul><p>This is the <strong>default choice</strong> for dynamic memory in modern C++.</p><h4>Creating a unique_ptr</h4><p>Preferred way (C++ 14+)</p><pre>#include &lt;memory&gt;<br><br>auto ptr = std::make_unique&lt;int&gt;(42);</pre><p>Why make_unique ?</p><ul><li>Exception-safe</li><li>Cleaner syntax</li><li>No risk of partial allocation leaks</li></ul><h4>RAII in Action</h4><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>class MyClass {<br>public:<br>    MyClass() { std::cout &lt;&lt; &quot;Constructed\n&quot;; }<br>    ~MyClass() { std::cout &lt;&lt; &quot;Destroyed\n&quot; }<br>};<br><br>void demo() {<br>    auto ptr = std::make_unique&lt;MyClass&gt;();<br>} // Destructor automatically called here</pre><p>No delete. No leaks. No crashes.</p><h4>Moving Ownership with std::move</h4><pre>auto a = std::make_unique&lt;int&gt;(10);<br>auto b = std::move(a); //ownership tranferred<br><br>if (!a) {<br>    std::cout &lt;&lt; &quot;a is empty\n&quot;;<br>}</pre><p>After the move, a == nullptr, b owns the memory.</p><p>To return unique_ptr from functions, below is efficient and idiomatic:</p><pre>std::unique_ptr&lt;MyClass&gt; create() {<br>    return std::make_unique&lt;MyClass&gt;();<br>}<br><br>int main() {<br>    auto obj = create();<br>}</pre><p>The compiler uses <strong>move semantics</strong> or <strong>RVO</strong>, so no copies occur.</p><h4>Managing Dynamic Arrays</h4><pre>auto arr = std::make_unique&lt;int[]&gt;(10);<br><br>arr[0] = 5;<br>arr[1] = 10;<br>// delete[] is automatic</pre><p>unique_ptr&lt;T[]&gt; automatically calls delete[].</p><h3>std::shared_ptr — Shared Ownership</h3><p>When Do You Need shared_ptr?</p><p>Use std::shared_ptr only when multiple parts of the program must own the same object. Examples: Factory functions, Cashes, Graph structures, Shared services. shared_ptr uses reference counting:</p><ul><li>Each copy increases the count</li><li>Each destruction decreases the count</li><li>When the count reaches zero -&gt; object is deleted</li></ul><p>When creating a shared_ptr, always prefer std::make_shared. By using this, benefits are: single memory allocation, better cache locality, and exception safety.</p><pre>#include &lt;memory&gt;<br><br>auto sp = std::make_shared&lt;int&gt;(42);</pre><h4>Shared Ownership Example</h4><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>class Resource {<br>public:<br>    Resource() { std::cout &lt;&lt; &quot;Created\n&quot;; }<br>    ~Resource() { std::cout &lt;&lt; &quot;Destroyed\n&quot;; }<br>};<br><br>int main() {<br>    auto a = std::make_shared&lt;Resource&gt;();<br>    std::cout &lt;&lt; a.use_count() &lt;&lt; &quot;\n&quot;; // 1<br><br>    auto b = a;<br>    std::cout &lt;&lt; a.use_count() &lt;&lt; &quot;\n&quot;; // 2<br>}</pre><p>Passing shared_ptr to Functions</p><pre>void process(std::shared_ptr&lt;Resource&gt; r) {<br>     std::cout &lt;&lt; r.use_count() &lt;&lt; &quot;\n&quot;;<br>}<br><br>process(a);</pre><p>Passing by value temporarily increases the reference count.</p><h4>The Problem: Circular References</h4><p>The Bug</p><pre>class A {<br>public:<br>    std::shared_ptr&lt;B&gt; b;<br>};<br><br>class B {<br>public:<br>    std::shared_ptr&lt;A&gt; a;<br>};</pre><p>This creates a <strong>cycle, </strong>which intrigues memory leak because reference counts never reach zero.</p><pre>A → shared_ptr → B<br>B → shared_ptr → A</pre><h3>std::weak_ptr — Non-Owning Observer</h3><p>What Is weak_ptr?</p><pre>std::weak_ptr&lt;T&gt;</pre><ul><li>Does NOT own the object</li><li>Does NOT increase reference count</li><li>Used to <strong>break cycles</strong></li><li>Must be converted using lock()</li></ul><h4><strong>Breaking the Cycle</strong></h4><pre>class Parent;<br><br>class Child {<br>public:<br>    std::weak_ptr&lt;Parent&gt; parent;<br>};<br><br>class Parent {<br>public:<br>    std::shared_ptr&lt;Child&gt; child;<br>}</pre><p>Ownership is now <strong>one-directional</strong>.</p><p>Using lock() Safely</p><pre>if (auto p = child-&gt;parent.lock()) {<br>    // Parent still exists<br>} else {<br>   // Parent already destroyed<br>}</pre><p>This prevents dangling pointer access.</p><p>Refactored with shared_ptr</p><pre>std::shared_ptr&lt;MyResource&gt; getResource() {<br>    static std::shared_ptr&lt;MyResource&gt; res =<br>        std::make_shared&lt;MyResource&gt;();<br>    return res;<br>}</pre><p>Now, ownership is clar, lifetime is automatic, no delete anywhere.</p><h3>Rule of Zero and Class Design</h3><p>One of the biggest advantages of smart pointers appears when they are used as class members. This is where modern C++ truly separates itself from old, error-prone designs. Consider a class that owns dynamically allocated memory using a raw pointer.</p><pre>class OldWidget {<br>public:<br>    int* data;<br><br>    OldWidget(int value) : data(new int(value)) {<br>        std::cout &lt;&lt; &quot;Constructed\n&quot;;<br>    }<br><br>    ~OldWidget() {<br>        std::cout &lt;&lt; &quot;Destroyed\n&quot;;<br>        delete data;<br>    }<br>};</pre><p>At first glance, this class looks correct. It allocates memory in the constructor and releases it in the destructor. However, the real problem appears as soon as the object is copied.</p><pre>OldWidget w1(10);<br>OldWidget w2 = w1; // Shallow copy!</pre><p>Both w1.data and w2.data now point to the <strong>same memory</strong>. When the objects go out of scope, the destructor is called twice, and delete is executed twice on the same address. This leads to <strong>undefined behavior</strong>, usually a crash.</p><p>The root cause is that raw pointers do not express ownership semantics. Because of this, the compiler-generated copy constructor performs a <strong>shallow copy</strong>, which is almost never correct for owning pointers.</p><p>To fix this properly using raw pointers, the developer must manually implement:</p><ul><li>A destructor</li><li>A copy constructor</li><li>A copy assignment operator</li><li>A move constructor</li><li>A move assignment operator</li></ul><p>This is known as the <strong>Rule of Five</strong>, and it is notoriously difficult to implement correctly.</p><h4>Refactoring with std::unique_ptr</h4><p>Now compare the same class rewritten using std::unique_ptr.</p><pre>#include &lt;memory&gt;<br><br>class NewWidget {<br>public:<br>    std::unique_ptr&lt;int&gt; data;<br><br>    NewWidget(int value) : data(std::make_unique&lt;int&gt;(value)) {<br>        std::cout &lt;&lt; &quot;Constructed\n&quot;;<br>    }<br>};</pre><p>That’s it.</p><p>No destructor.</p><p>No copy constructor.</p><p>No assignment operators.</p><p>The class is now <strong>Rule of Zero compliant</strong>.</p><p>This works because std::unique_ptr already knows how to:</p><ul><li>Destroy the resource</li><li>Prevent copying</li><li>Move ownership safely</li></ul><p>By delegating memory management to a smart pointer, the class itself no longer needs to manage resources directly. The compiler-generated special member functions are now correct by default.</p><p>If copying is required, it must be <strong>explicitly designed</strong>, usually via a clone() function.</p><pre>std::unique_ptr&lt;NewWidget&gt; clone() const {<br>    return std::make_unique&lt;NewWidget&gt;(*data);<br>}</pre><p>This makes ownership and intent clear and avoids accidental shallow copies.</p><h3>Performance Considerations</h3><p>Smart pointers are designed to be safe first, but performance still matters — especially in C++. The good news is that std::unique_ptr has almost no performance cost compared to raw pointers. Internally, it typically stores just a single raw pointer, and its destructor simply calls delete. Move operations are cheap and often optimized away entirely by the compiler.</p><p>For this reason, std::unique_ptr should be the <strong>default choice</strong> whenever exclusive ownership is sufficient.</p><p>std::shared_ptr, on the other hand, has unavoidable overhead. Each copy or destruction modifies a reference count, and for thread safety, these operations are usually atomic. This makes shared_ptr slightly slower and more memory-hungry than unique_ptr.</p><pre>auto a = std::make_shared&lt;int&gt;(10);<br>auto b = a; // automic ref count increment</pre><p>Additionally, shared_ptr stores a pointer to a separate control block that contains the reference count and deleter. This means more memory usage and more indirection.</p><p>Because of this, std::shared_ptr should be used <strong>only when shared ownership is truly required</strong>, not as a convenience or default.</p><p>Whenever you do use shared_ptr, std::make_shared is strongly recommended because it allocates both the object and its control block in a single memory allocation, which is faster and more cache-friendly.</p><h3>Final Thoughts</h3><p>Modern C++ encourages developers to think about<strong> ownership</strong>, not memory addresses. Smart pointers encode ownership rules directly into the type system, allowing the compiler to enforce correct behavior.</p><p>std::unique_ptr expresses exclusive ownership.</p><p>std::shared_ptr expresses shared ownership.</p><p>std::weak_ptr expresses observation without ownership.</p><p>Raw pointers still exist, but they should be used only for non-owning access or interperability with C APIs.</p><p>In practice, mastering smart pointers eliminates most memory management bugs before they ever reach runtime.</p><p>Reference: Udacity C++ Nanodegree | Memory Management Course</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fd424ca5620" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ Move Semantics: From Copy to Efficient Resource Transfer]]></title>
            <link>https://medium.com/@su-paris/c-move-semantics-from-copy-to-efficient-resource-transfer-aa7bbe145dd7?source=rss-6259b032bb9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa7bbe145dd7</guid>
            <category><![CDATA[move-semantics]]></category>
            <dc:creator><![CDATA[Seulgie Han]]></dc:creator>
            <pubDate>Sat, 13 Dec 2025 22:57:47 GMT</pubDate>
            <atom:updated>2025-12-13T22:57:47.746Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Source &amp; Purpose: </strong>Based on Udacity C++ Nanodegree — Course3: Memory Management, this post is intended to help consolidate learning about move semantics and resource management in C++.</p><p>If you’ve been working with dynamic memory and copy constructors, you know that <strong>deep copying large objects </strong>can be slow and inefficient. Enter <strong>Move Semantics</strong>, a C++ 11 feature that allows us to <strong>transfer ownership of resources instead of duplicating them.</strong> In this post, we’ll explore Move Semantics, Move Constructors, Move Assignment Operators, and how to use std::move effectively.</p><h4>1️⃣ Why Move Semantics Exist</h4><p>Deep copying large objects is safe but <strong>expensive</strong>:</p><pre>DynamicArray arr1(1000000);<br>DynamicArray arr2 = arr1; // 1 million elements copied → slow</pre><ul><li>Copying element-by-element consumes CPU and memory.</li><li><strong>Move semantics </strong>avoid this by “stealing” resources from<strong> temporary objects</strong> (rvalues) instead of duplicating them.</li></ul><h4>2️⃣ Lvalues vs Rvalues</h4><ul><li><strong>Lvalue:</strong> Named object, persistent memory (eg. DynamicArray arr1(10); )</li><li><strong>Rvalue</strong>: Temporary object, disappears after expression</li></ul><pre>DynamicArray(20); // temporary Rvalue<br>arr1 = DynamicArray(20); // creates temporary → can move</pre><p><strong>Move semantics only apply to Rvalues </strong>because the compiler can safely transfer ownership without affecting other code.</p><h4>3️⃣ Move Constructor: Stealing Resources</h4><p>Move constructor creates a new object by taking ownership of an rvalue’s resources.</p><pre>class MyDynamicClass {<br>    int* m_data;<br>public:<br>    MyDynamicClass(int value) {<br>        m_data = new int(value);<br>        std::cout &lt;&lt; &quot;Constructor: allocated &quot; &lt;&lt; value &lt;&lt; &quot;\n&quot;;<br>    }<br><br>    MyDynamicClass(MyDynamicClass&amp;&amp; other) noexcept {<br>        std::cout &lt;&lt; &quot;Move constructor called!\n&quot;;<br>        m_data = other.m_data;   // Steal pointer<br>        other.m_data = nullptr;  // Leave source empty<br>    }<br><br>    ~MyDynamicClass() {<br>        if (m_data) delete m_data;<br>    }<br><br>    void printValue() const {<br>        if (m_data) std::cout &lt;&lt; &quot;Value: &quot; &lt;&lt; *m_data &lt;&lt; &quot;\n&quot;;<br>        else std::cout &lt;&lt; &quot;Value: (moved-from)\n&quot;;<br>    }<br>};</pre><p>Usage:</p><pre>MyDynamicClass a(10);<br>MyDynamicClass b = std::move(a); // Move constructor called<br>b.printValue(); // 10<br>a.printValue(); // moved-from</pre><ol><li>b takes a&#39;s pointer</li><li>a pointer set to nullptr.</li><li>No deep copy occurs -&gt; fast!</li></ol><h4>4️⃣ Move Assignment Operator: Moving to Existing Objects</h4><p>Move assignment handles already-existing objects:</p><pre>MyDynamicClass&amp; operator=(MyDynamicClass&amp;&amp; other) noexcept {<br>    if (this != &amp;other) {        // Avoid self-assignment<br>        delete m_data;           // Free existing memory<br>        m_data = other.m_data;   // Steal resources<br>        other.m_data = nullptr;  // Leave source empty<br>    }<br>    return *this;<br>}</pre><p><strong>Example:</strong></p><pre>MyDynamicClass c(20);<br>c = MyDynamicClass(30); // Move assignment called<br>c.printValue(); // 30</pre><ul><li>Avoids expensive deep copy</li><li>Source object is safe but emptied</li></ul><h4>5️⃣ std::move: Explicitly Turning Lvalues into Rvalues</h4><p>std::move doesn’t move anything — it <strong>casts an Lvalue to Rvalue</strong>:</p><pre>MyDynamicClass original(50);<br>MyDynamicClass moved = std::move(original); // forces move</pre><ul><li>Signals compiler to use <strong>move constructor</strong></li><li>original is now a <strong>valid but unspecified state</strong></li><li>You should<strong> not read from original </strong>after move</li></ul><p><strong>Real-world analogy:</strong></p><blockquote>“Here’s my temporary object, feel free to take its memory. I don’t need it anymore.”</blockquote><h4>6️⃣ Using Move in Functions</h4><pre>void transferOwnership(MyDynamicClass&amp; dest, MyDynamicClass&amp; source) {<br>    dest = std::move(source); // Forces move assignment<br>}<br><br>int main() {<br>    MyDynamicClass arr1(100);<br>    MyDynamicClass arr2(200);<br><br>    transferOwnership(arr1, arr2);<br>    arr1.printValue(); // 200<br>    arr2.printValue(); // moved-from<br>}</pre><ul><li>arr2 is Lvalue -&gt; normally would copy</li><li>std::move(arr2) -&gt; moves resources efficiently</li><li>arr2 emptied safely after transfer</li></ul><h4>7️⃣ Automatic Move from Temporary Objects</h4><pre>MyDynamicClass createTempObject() {<br>    return MyDynamicClass(99); // Rvalue<br>}<br><br>MyDynamicClass obj = createTempObject(); // move constructor used</pre><ul><li>Temporary returned object is an Rvalue</li><li>Compiler automatically applies move semantics</li><li>Avoids unnecessary deep copy</li></ul><h3>Key Takeaways</h3><ol><li><strong>Move semantics</strong>: Boost performance by avoiding deep copies.</li><li><strong>Move constructor &amp; assignment</strong>: Steal resources from rvalues.</li><li><strong>std::move</strong>: Cast Lvalue -&gt; Rvalue for explicit move.</li><li>Moved-from objects remain <strong>valid but empty</strong>.</li><li>Especially useful for <strong>containers, large strings, arrays</strong>.</li></ol><p>Modern C++ move semantics make programs faster and safer by transferring ownership of memory without copying. By implementing move constructors, move assignments, and using std::move wisely, you:</p><ul><li>Reduce memory overhead</li><li>Avoid unnecessary deep copies</li><li>Maintain safe memory management</li></ul><p>Move semantics complement the Rule of Three/Five, giving C++ developers both performance and reliability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa7bbe145dd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Copy Control, Deep Copy, and the Rule of Three in C++]]></title>
            <link>https://medium.com/@su-paris/copy-control-deep-copy-and-the-rule-of-three-in-c-25d4652e833a?source=rss-6259b032bb9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/25d4652e833a</guid>
            <category><![CDATA[shallow-vs-deep-copy]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Seulgie Han]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 15:09:43 GMT</pubDate>
            <atom:updated>2025-12-11T15:09:43.896Z</atom:updated>
            <content:encoded><![CDATA[<p>Study notes &amp; reflections based on Udacity C++ Nanodegree — Course 3: Memory Management</p><p>Managing memory safely is one of the most essential and most misunderstood parts of modern C++. Many bugs — crashes, corrupted data, double frees — can be traced back to one root problem: <strong>the compiler-generated copy behavior does not work correctly when your class owns raw dynamic memory.</strong></p><p>In this post, we’ll explore:</p><ul><li>Why C++’s default copy behavior is dangerous when raw pointers are involved</li><li>The “shallow copy” problem and what actually causes crashes</li><li>How the Rule of Three ensures safe memory ownership</li><li>How to implement deep copy correctly</li><li>A beginner-friendly walkthrough of an exercise that fixes a broken class</li></ul><p>This is part learning, part review, and part documentation of my understanding while going through Udacity’s Memory Management course.</p><h3>🚨 The Root Problem: Shallow Copy with Raw Pointers</h3><p>C++ gives every class a <strong>default copy constructor</strong> and <strong>default copy assignment operator.</strong> These automatically copy all members “as they are.” Normally, this is fine for integers, doubles, and objects that manage their own resources like std::string.</p><p>But for classes that hold <strong>raw pointers</strong>, this becomes a serious problem.</p><p>What the compiler does by default:</p><pre>this-&gt;m_buffer = other.m_buffer;   // Copies only the pointer (address)</pre><p>This means <strong>two distinct objects now think they own the same block of heap memory. </strong>Ownership confusion is the root cause of two dangerous failure modes.</p><h4>❌ Scenario 1: Double Deletion (The Crash!)</h4><p>Consider this simplified example:</p><pre>MyString s1(&quot;Hello&quot;);<br>MyString s2 = s1;   // shallow copy → same m_buffer pointer</pre><p>Both s1 and s2 now believe they own the same buffer.</p><p>When s2 is destroyed, destructor deletes the buffer. When s1 is destroyed, destructor tries to delte the<strong> same</strong> buffer again. Boom -&gt; <strong>double free, </strong>heap corruption, crash.</p><h4>❌ Scenario 2: Corrupted Data (Silent Logic Errors)</h4><p>Because both objects share the same memory:</p><pre>s2.m_buffer[0] = &#39;J&#39;;<br>std::cout &lt;&lt; s1.m_buffer;   // prints: Jello</pre><p><strong>Modifying one object unexpectedly modifies the other. </strong>There is no compiler warning, no error message — just bad data. For beginners, this bug is especially painful because the code looks completely correct.</p><h3>✔️ The Fix: Deep Copy</h3><p>A <strong>deep copy</strong> gives each object its own memory:</p><ol><li>Allocate new heap memory</li><li>Copy the content, not the pointer</li><li>Ensure each object has independent ownership</li></ol><pre>m_buffer = new char[strlen(other.m_buffer) + 1];<br>strcpy(m_buffer, other.m_buffer);</pre><p>Now each object owns its own memory block — safe and predictable.</p><h3>The Rule of Three</h3><p>If your class allows dynamic memory (via new) and cleans it up in the destructor (via delete), then you <strong>must</strong> also define:</p><ol><li><strong>Destructor</strong></li><li><strong>Copy Constructor</strong></li><li><strong>Copy Assignment Operator</strong></li></ol><p>Otherwise, shallow copies will break your program. This is called the<strong> Rule of Three</strong>, and it is the foundation of correct resource management before C++ 11’s move semantics.</p><h3>Implementing Correct Copy Control: A Minimal Example</h3><p>Let’s walk through a clean, beginner-friendly class that manages an integer on the heap.</p><ul><li><strong>Constructor</strong> : Allocate memory, initialize the value</li><li><strong>Destructor</strong> : Free memory, prevent memory leaks</li><li><strong>Copy Constructor</strong> : Allocate new memory, copy value, not pointer</li><li><strong>Copy Assignment</strong> : Guard against self-assignment, delete old memory, deep copy</li></ul><h3>Exercise: Fixing a Buggy Class (Beginner-Friendly Walkthrough)</h3><p>Here is the <strong>broken class</strong> from the exercise:</p><pre>class Container {<br>public:<br>    int* data;<br><br>    Container(int val) {<br>        data = new int;<br>        *data = val;<br>    }<br><br>    // ❌ BUG: Shallow copy!<br>    Container(const Container&amp; other) {<br>        data = other.data;<br>    }<br><br>    ~Container() {<br>        delete data;<br>    }<br>};</pre><p><strong>What’s wrong?</strong></p><p>The copy constructor does:</p><pre>data = other.data;   // Copies pointer, not value</pre><ul><li>Both objects share the same memory</li><li>Double deletion crash</li><li>Data corruption</li></ul><h4>✔ Fixing It: Deep Copy Implementation</h4><p>Here is the corrected copy constructor:</p><pre>Container(const Container&amp; other) {<br>    data = new int;        // allocate new memory<br>    *data = *other.data;   // deep copy the value<br>}</pre><p><strong>Why this fixes the problem:</strong></p><ul><li>The new object receives its <strong>own</strong> heap memory</li><li>Modifying one object does <strong>not </strong>affect the other</li><li>Each destructor deletes a different memory block</li><li>No more double deletion</li></ul><h3>Summary</h3><p>In this first section of the topic, we covered:</p><ul><li>Why shallow copy is dangerous with raw pointers</li><li>How double deletion and silent data corruption occur</li><li>What deep copy is and why it solves these issues</li><li>The Rule of Three and why it matters</li><li>A full explanation of fixing a buggy copy constructor</li></ul><p>These are the foundations of C++ memory safety and prepare us for the next steps: <strong>move semantics, the Rule of Five, and the Rule of Zero.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25d4652e833a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remote Sensing: How Satellites Convert Invisible Radiation Into Earth Data]]></title>
            <link>https://medium.com/@su-paris/remote-sensing-how-satellites-convert-invisible-radiation-into-earth-data-5f950a872f0c?source=rss-6259b032bb9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f950a872f0c</guid>
            <category><![CDATA[remote-sensing]]></category>
            <dc:creator><![CDATA[Seulgie Han]]></dc:creator>
            <pubDate>Wed, 10 Dec 2025 23:00:40 GMT</pubDate>
            <atom:updated>2025-12-10T23:00:40.785Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Note: This post series is a distilled summary of concepts from Lecture 1–4 of the <a href="https://www.youtube.com/playlist?list=PLLy_2iUCG87CDlroZBlwwBllYwz7KxVtA">Remote Sensing series</a> on YouTube. I created this as part of my own learning process to strengthen my understanding of remote sensing.</blockquote><p>If you work in data, you know the challenge: garbage in, garbage out. Remote sensing is one of the richest sources of Earth-scale data you can get — but its raw form begins as something far less tangible: <strong>electromagnetic radiation.</strong></p><p>In this post, we’re going to unpack how satellites collect radiation, turn it into pixels, and eventually into the analytics used across climate tech, agriculture, energy, and defense. First, let’s focus on <strong>the basic physics and system architecture </strong>— without heavy math.</p><h3>Why Remote Sensing Exists</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fi7nBzj5VS4bFWluOZ6ZAQ.png" /></figure><p>Remote sensing solves problems that ground sensors or manual surveys simply cannot:</p><ul><li>We need <strong>planet-scale coverage</strong></li><li>We need <strong>consistent, repeated monitoring</strong></li><li>We need <strong>multispectral information</strong> (something eyes can’t see)</li><li>We need <strong>data in hostile or inaccessible regions</strong></li></ul><p>From crop monitoring to wildfire tracking, the core value proposition is simple:</p><blockquote>Remote sensing measures the Earth without touching it.</blockquote><h3>The Remote Sensing Pipeline</h3><p>Think of remote sensing as a seven-step data pipeline.</p><h4>1. Energy Source</h4><p>Radiation must originate from somewhere:</p><ul><li><strong>Sunlight</strong> (visible, NIR, SWIR)</li><li><strong>Earth’s own heat</strong> (thermal IR)</li><li><strong>Artificial pulses </strong>(RADAR, LiDAR)</li></ul><p>Without energy, there’s no signal to measure.</p><h4>2. Interaction With the Atmosphere (Part 1)</h4><p>Radiation traveling toward the surface hits molecules, droplets, and aerosols. Three main effects occur:</p><ul><li><strong>Absorption</strong> -&gt; energy disappears into atmospheric gases</li><li><strong>Scattering</strong> -&gt; energy is redirected</li><li><strong>Transmission</strong> -&gt; remaining energy reaches the surface</li></ul><p>Why this matters:</p><blockquote><strong>The atmosphere acts as a filter.</strong> If a wavelength is heavily absorbed, you cannot build a remote sensing system for it.</blockquote><h4>3. Interaction With the Surface</h4><p>This is where the magic happens.</p><p>Different materials have different “spectral personalities”:</p><ul><li>Vegetation tends to absorb red, reflect near-infrared</li><li>Water tends to absorb most wavelengths -&gt; appears dark</li><li>Soil tends to reflect moderately across many bands</li><li>Snow/Ice tends to be vey reflective in visible but absorbs in SWIR</li></ul><p>These behaviors generate what we call a <strong>spectral signature</strong> — like a fingerprint for materials.</p><h4>4. Atmospheric Path (Part 2)</h4><p>Now the reflected/emitted energy travels back upward. It getes distorted again by the same atmospheric effects. This round-trip distortion is why satellite data requires <strong>atmospheric correction</strong>.</p><h4>5. Sensor Detection</h4><p>Sensors don’t capture an image. They measure<strong> radiance</strong> — physical energy per unit wavelength. Each measurement becomes a number stored inside a pixel.</p><h4>6. Transmission &amp; Processing</h4><p>Data travels to ground stations, undergoes:</p><ul><li>geometric correction</li><li>radiometric calibration</li><li>geo-referencing</li><li>formatting</li></ul><p>Finally you get an image that can be analyzed in GIS or Python.</p><h4>7. Interpretation &amp; Application</h4><p>This is what most people<em> think </em>remote sensing is — but it’s just the final stage. Deep learning models, geospatial analytics, physical models, and domain expertise turn imagery into insights:</p><ul><li>land cover classification</li><li>vegetation health indices</li><li>urban expansion</li><li>anomaly detection</li></ul><h3>The Electromagnetic Spectrum for Remote Sensing</h3><p>The EM spectrum ranges from gamma rays to radio waves. Remote sensing only uses certain “windows”. Here’s the short version:</p><ul><li><strong>Visible (0.4~0.7 μm)</strong> : Color, human vision, high spatial detail.</li><li><strong>NIR &amp; SWIR (0.7 ~ 3 μm)</strong> : Vegetation structure, plant water content, soil and mineral chemistry.</li><li><strong>Thermal IR (3–100 μm)</strong> : Earth’s emitted heat -&gt; land surface temperature, fires.</li><li><strong>Microwave (1mm — 1m)</strong> : Penetrates clouds -&gt; day/night imaging, soil moisture, structure detection, SAR.</li></ul><h3>Understanding the Key Radiation Laws</h3><p>Let’s look at three physics principles to understand basic remote sensing.</p><h4>Stefan-Boltzmann Law (Total Emitted Energy)</h4><blockquote>Objects emit more energy as they get hotter. And the increase is to the <strong>fourth power</strong> of temperature.</blockquote><p>Meaning:</p><ul><li>A small temperature increase -&gt; a huge jump in emitted energy</li><li>Thermal sensors are extremely sensitive</li></ul><h4>Wien’s Displacement Law (Peak Wavelength)</h4><p>This one is intuitive:</p><blockquote>Hot objects emit energy at shorter wavelengths. Cool objects emit at longer wavelengths.</blockquote><p>Sun -&gt; peaks in visible</p><p>Earth -&gt; peaks in thermal IR</p><h4>Planck’s Law (Full Spectrum Shape)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*G2IH-pHzVExiqw6aScGI8A.png" /></figure><p>Planck described how much energy is emitted at each wavelength.</p><p>You don’t need the equation — just understand this:</p><ul><li>Shorter wavelengths have <strong>higher-energy photons</strong></li><li>Longer wavelengths have <strong>lower-energy photons</strong></li><li>Therefore, sensors for longer wavelengths need<strong> bigger detectors or longer exposure</strong> to collect enough signal</li></ul><p>This explains why thermal IR images have lower spatial resolution. One consequence of Planck’s laws is crucial for data professionals:</p><blockquote>Short wavelengths deliver more photons per unit energy. Long wavelengths deliver fewer photons.</blockquote><p>As a result, visible/NIR have high resolution with lots of photons, whereas thermal IR will have coarse resolution with fewer photons per second.</p><h3>Wrapping Up</h3><p>In this post, we explored the remote sensing pipeline, the EM spectrum, the atmosphere’s filtering role, spectral responses, thermal vs. visible radiation, and why sensors behave so differently across wavelengths.</p><p>In the next post, we’ll go deeper into how sensors encode all this into digital data: pixels, bit depth, spatial resolution, multispectral vs hyperspectral imaging, and more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f950a872f0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Double Deletion, Wild Pointers, and Dangling Pointers in C++]]></title>
            <link>https://medium.com/@su-paris/understanding-double-deletion-wild-pointers-and-dangling-pointers-in-c-e43bbaea2cb3?source=rss-6259b032bb9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e43bbaea2cb3</guid>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[dangling-pointer]]></category>
            <category><![CDATA[raii]]></category>
            <dc:creator><![CDATA[Seulgie Han]]></dc:creator>
            <pubDate>Tue, 09 Dec 2025 13:05:40 GMT</pubDate>
            <atom:updated>2025-12-09T13:05:40.783Z</atom:updated>
            <content:encoded><![CDATA[<p>Manual memory management gives C++ its power — but also its sharpest edges. If you mismanage ownership, you won’t simply get a bug; you’ll get crashes, corrupted memory, or behavior so unpredictable that debugging becomes a nightmare. In this post, we’ll walk through two classic mistakes:</p><ul><li>Double Deletion</li><li>Wild &amp; Dangling Pointers</li></ul><p>We’ll examine why they occur, how to fix them, and how to build safe mental models for memory ownership.</p><h3>Double Deletion: When Ownership Goes Wrong</h3><p>A double deletion happens when the same dynamically allocated block of memory is freed more than once. Here’s a simple — but dangerous — example:</p><pre>#include &lt;iostream&gt;<br><br>class MyResource {<br>public:<br>    int* data;<br>    MyResource(int val) {<br>        data = new int(val);<br>        std::cout &lt;&lt; &quot;Resource created at address &quot; &lt;&lt; data &lt;&lt; std::endl;<br>    }<br>    ~MyResource() {<br>        std::cout &lt;&lt; &quot;Resource destroyed, deleting data at &quot; &lt;&lt; data &lt;&lt; std::endl;<br>        delete data;<br>    }<br>};<br><br>int main() {<br>    MyResource* ptr1 = new MyResource(10);<br>    MyResource* ptr2 = ptr1; // ptr2 now points to the same object as ptr1<br><br>    // PROBLEM: deleting the same object twice<br>    delete ptr1;<br>    delete ptr2;<br><br>    return 0;<br>}</pre><p>Why this crashes? ptr1 and ptr2 point to the same MyResource instance. Deleting ptr1 destroys the object and frees data. Deleting ptr2 attempts to destroy an object that no longer exists -&gt; <strong>undefined behavior. </strong>This is a pure ownership violation.</p><h3>✅ Fix: Ensure Only One Owner</h3><p>You can fix this in several safe ways:</p><h4>Option A: Avoid duplicating raw ownership</h4><p>Correct and simplest fix:</p><pre>int main() {<br>    MyResource* ptr1 = new MyResource(10);<br><br>    delete ptr1;  // delete only once<br><br>    return 0;<br>}</pre><h4>Option B: Use std::unique_ptr</h4><p>The real modern C++ solution:</p><pre>#include &lt;memory&gt;<br><br>int main() {<br>    std::unique_ptr&lt;MyResource&gt; ptr1 = std::make_unique&lt;MyResource&gt;(10);<br><br>    // Ownership cannot be duplicated accidentally.<br>}</pre><h3>Wild and Dangling Pointers</h3><p>Wild and dangling pointers are another category of dangerous memory bugs.</p><ul><li><strong>Wild pointer:</strong> An uninitialized pointer pointing to an unknown location.</li><li><strong>Dangling pointer: </strong>A pointer that used to point to valid memory but that memory has been freed.</li></ul><p>Consider the following code:</p><pre>#include &lt;iostream&gt;<br><br>int* create_integer() {<br>    int* some_int; // Wild pointer<br>    *some_int = 100;<br>    return some_int;<br>}</pre><p>some_int is uninitialized — it could point anywhere. Writing to *some_int corrupts arbitrary memory. Now the main function:</p><pre>int main() {<br>    int* my_ptr = new int(50);<br>    std::cout &lt;&lt; &quot;Value before delete: &quot; &lt;&lt; *my_ptr &lt;&lt; std::endl;<br><br>    delete my_ptr;   // memory freed<br>    std::cout &lt;&lt; &quot;Value after delete: &quot; &lt;&lt; *my_ptr &lt;&lt; std::endl; // Dangling pointer<br><br>    int* ptr_from_function = create_integer();<br>    std::cout &lt;&lt; &quot;Value from function: &quot; &lt;&lt; *ptr_from_function &lt;&lt; std::endl;<br><br>    delete ptr_from_function;<br>    return 0;<br>}</pre><h4>❗ What’s wrong here?</h4><ol><li>my_ptr is dangling after delete.</li><li>create_integer() returns a <strong>wild pointer.</strong> The program crashes before the dangling pointer problem even matters.</li></ol><h3>✅ Fixing the Wild and Dangling Pointer Bugs</h3><h4>Fix 1: Initialize the pointer properly</h4><pre>int* create_integer() {<br>    int* some_int = new int(100); // allocate properly<br>    return some_int;<br>}</pre><h4>Fix 2: Avoid using my_ptr after deleting</h4><pre>delete my_ptr;<br>my_ptr = nullptr; // defensive habit</pre><h4>Fixed Program</h4><pre>#include &lt;iostream&gt;<br><br>int* create_integer() {<br>    int* some_int = new int(100);  // FIX: allocate properly<br>    return some_int;<br>}<br><br>int main() {<br>    int* my_ptr = new int(50);<br>    std::cout &lt;&lt; &quot;Value before delete: &quot; &lt;&lt; *my_ptr &lt;&lt; std::endl;<br><br>    delete my_ptr;<br>    my_ptr = nullptr;  // FIX: avoid dangling pointer use<br><br>    int* ptr_from_function = create_integer();<br>    std::cout &lt;&lt; &quot;Value from function: &quot; &lt;&lt; *ptr_from_function &lt;&lt; std::endl;<br><br>    delete ptr_from_function;<br><br>    return 0;<br>}</pre><h3>Key Takeaways</h3><ul><li>A pointer is not memory; it is merely a reference to memory. Copying a raw pointer does not copy ownership.</li><li>Deleting memory twice is a catastrophic ownership violation.</li><li>Uninitialized pointers (wild pointers) are as dangerous as loaded guns.</li><li>A pointer that outlives its memory (dangling pointer) invites undefined behavior.</li><li>The best long-term solution is to embrace RAII and smart pointers like std::unique_ptr and std::shared_ptr.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e43bbaea2cb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>