SyntaxPilot
Courses/C++ Coding Questions/Lesson 26
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

C++ Coding Questions · Lesson 26 of 30

Pointers and memory questions

returning a reference to a local (dangling)new[] with delete (mismatch)memory leak vs unique_ptr and shared_ptr counts

These are the notes for C++ Coding Questions, episode 26, placement practice for people who finished the SyntaxPilot C++ course. Memory questions are interview favourites because the code looks fine and still crashes. Three classics: a function that returns a reference to a local variable (a dangling reference), an array made with new[] and freed with the wrong delete, and a memory leak from an early return, fixed with unique_ptr, plus shared_ptr and its owner count.

Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the cost.

Every program was compiled with g++ -Wall -O2 -std=c++17 main.cpp -o main (g++ 13.3, Linux x86-64), the SyntaxPilot compiler's C++ command with warnings on, and every output below is real, including the compiler errors, warnings and crashes.

Real-life pictures

In real life In C++
A friend gives you his hostel room number, not the parcel returning a reference instead of the value
He checks out that evening; the room is cleared the local variable is destroyed when the function returns
Room 42 is empty, or has someone else's things a dangling reference: undefined behaviour
He hands you the parcel itself return by value
Three cinema seats in ONE booking new Seat[3]
The counter stores "3 seats" with the booking new[] stores the element count
Cancelling it as if it were one seat delete instead of delete[]
Students who leave by the side door with a library book an early return that skips delete: a leak
A book with an auto-return tag, returned at any door unique_ptr
The last person out of a shared room switches off the light shared_ptr: the last owner frees the object

Q1: Returning a reference to a local (dangling)

Problem. Write makeToken(id) that builds the token "TKN-<id>". Input 42 → your token: TKN-42; input 7 → TKN-7.

Think out loud. A reference (string&) is another name for an existing variable: no copy is made. Someone suggests: "return const string& so we don't copy the string." Is that safe? The question is how long the thing being referred to lives.

The obvious attempt

#include <iostream>
#include <string>
using namespace std;

const string& makeToken(int id) {
    string token = "TKN-" + to_string(id);   // a local variable
    return token;                        // a reference to it
}

int main() {
    int id;
    cin >> id;
    cout << "getting your token..." << endl;
    const string& t = makeToken(id);
    cout << "your token: " << t << endl;
    return 0;
}

Input 42. Compiler output, program output, and the crash:

main.cpp: In function 'const std::string& makeToken(int)':
main.cpp:7:12: warning: reference to local variable 'token' returned [-Wreturn-local-addr]
    7 |     return token;                        // a reference to it
      |            ^~~~~
main.cpp:6:12: note: declared here
    6 |     string token = "TKN-" + to_string(id);   // a local variable
      |            ^~~~~
getting your token...
Segmentation fault

(endl prints and flushes each line at once, so the first line appears before the crash. With "\n" the program's buffered output would be lost when it crashes.)

Why

token is a local variable: it lives on the stack inside makeToken and is destroyed the moment the function returns. The returned reference refers to an object that no longer exists: a dangling reference. Using it is undefined behaviour (UB): the language gives no meaning to the program. Here, g++ with -O2 crashed with a segmentation fault (the program touched memory it was not allowed to). Another compiler or flag might print garbage, or even the right text by luck. A program that "works" with UB is still wrong.

The same applies to returning a pointer to a local (return &token;), and to keeping a reference to an element of a vector that later grows (the elements move to a new block).

The fix: return by value

#include <iostream>
#include <string>
using namespace std;

string makeToken(int id) {               // return the string itself
    string token = "TKN-" + to_string(id);
    return token;                        // moved out, not copied
}

int main() {
    int id;
    cin >> id;
    cout << "getting your token..." << endl;
    string t = makeToken(id);
    cout << "your token: " << t << endl;
    return 0;
}
Input Output
42 getting your token..., your token: TKN-42
7 getting your token..., your token: TKN-7

Returning by value is not slow: the compiler either builds token directly in the caller's variable (copy elision, also called NRVO) or moves it out (it hands over the string's buffer). Returning a reference is only safe when the object outlives the function: a member of an object that is still alive, an element of a container the caller owns, or a static variable.

Cost. Building the token is O(L) time and space for a token of length L. Returning it is O(1) extra.

Q2: new[] with the wrong delete

Problem. Book a row of 3 Seat objects on the heap with new Seat[3], number them 1 to 3, then free them. Each Seat prints a line when it is freed. Expected:

booked 3 seats
seat 3 freed
seat 2 freed
seat 1 freed
done

Think out loud. The heap is memory you ask for with new and must give back yourself with delete. There are two forms: new T / delete p for one object, and new T[n] / delete[] p for an array.

The obvious attempt

#include <iostream>
using namespace std;

struct Seat {
    int no;
    Seat() : no(0) {}
    ~Seat() { cout << "seat " << no << " freed" << endl; }
};

int main() {
    Seat* row = new Seat[3];             // three seats in one block
    for (int i = 0; i < 3; i++) row[i].no = i + 1;
    cout << "booked 3 seats" << endl;
    delete row;                          // the obvious delete
    cout << "done" << endl;
    return 0;
}

Compiler output, program output, and the crash:

main.cpp: In function 'int main()':
main.cpp:14:12: warning: 'void operator delete(void*, std::size_t)' called on pointer returned from a mismatched allocation function [-Wmismatched-new-delete]
   14 |     delete row;                          // the obvious delete
      |            ^~~
main.cpp:11:27: note: returned from 'void* operator new [](std::size_t)'
   11 |     Seat* row = new Seat[3];             // three seats in one block
      |                           ^
booked 3 seats
seat 1 freed
munmap_chunk(): invalid pointer
Aborted

done is never printed; the program was aborted (exit code 134, signal SIGABRT).

Why

For an array of objects that have a destructor, new Seat[3] asks for a little extra memory and stores the count (3) just in front of the seats, so that delete[] later knows how many destructors to run. row points at seat 1, after the hidden count.

Plain delete row thinks row is one object: it runs one destructor (seat 1 freed) and then gives the memory system the address row, which is not the start of the block it handed out (the count is in front). The allocator detects a bad address: munmap_chunk(): invalid pointer, and aborts.

Any mismatch (new[] with delete, new with delete[], malloc with delete) is undefined behaviour. For new int[5] + delete there may be no visible crash (g++ still warns), but it is just as wrong.

The fix

    delete[] row;                        // [] matches new[]

Output:

booked 3 seats
seat 3 freed
seat 2 freed
seat 1 freed
done

delete[] destroys the elements in reverse order (the last one built is the first destroyed, just like members in episode 25), then frees the whole block.

Better still: don't use new[] at all. vector<Seat> row(3); allocates, numbers can be set the same way, and it frees itself when it goes out of scope, on every path, with no way to pick the wrong delete.

Cost. Freeing n seats is O(n) (one destructor each).

Q3: Memory leaks, unique_ptr and shared_ptr

Problem. process(id) creates an Order with new. For even ids the payment fails and the function returns early. After processing 1,000 orders, how many are still in memory? Expected: 0.

Think out loud. A memory leak is memory taken with new and never given back. One leak is small; a server that leaks on every request slowly eats all its RAM and crashes after days. To see a leak, Order keeps a static counter: a static data member is one variable shared by all objects of the class (not one per object). The constructor adds 1, the destructor subtracts 1.

The obvious attempt

#include <iostream>
#include <string>
#include <memory>
using namespace std;

struct Order {
    static int alive;                    // how many Orders exist right now
    string item;
    Order(string s) : item(s) { alive++; }
    ~Order() { alive--; }
};
int Order::alive = 0;

bool process(int id) {
    Order* o = new Order("chai #" + to_string(id));
    if (id % 2 == 0) return false;       // even ids: payment failed, leave early
    delete o;
    return true;
}

int main() {
    for (int id = 1; id <= 1000; id++) process(id);
    cout << "orders still in memory: " << Order::alive << "\n";
    return 0;
}

Output (no error, no warning):

orders still in memory: 500

Why

A raw pointer (Order*) is just an address: it frees nothing by itself. Every way out of the function needs its own delete, and the early return for the 500 even ids skipped it. The same happens when an exception is thrown between new and delete.

The fix: unique_ptr (RAII)

Let an object own the memory. A local object's destructor runs on every exit path (normal return, early return, exception), so put the delete in a destructor. This idea is called RAII ("Resource Acquisition Is Initialization": acquire in the constructor, release in the destructor). std::unique_ptr is exactly that for one heap object.

#include <iostream>
#include <string>
#include <memory>
using namespace std;

struct Order {
    static int alive;                    // how many Orders exist right now
    string item;
    Order(string s) : item(s) { alive++; }
    ~Order() { alive--; }
};
int Order::alive = 0;

bool process(int id) {
    auto o = make_unique<Order>("chai #" + to_string(id));
    if (id % 2 == 0) return false;       // leave early: o is still freed
    return true;
}

int main() {
    for (int id = 1; id <= 1000; id++) process(id);
    cout << "orders still in memory: " << Order::alive << "\n";
    return 0;
}

Output:

orders still in memory: 0

unique_ptr has exactly one owner

Copying a unique_ptr would create two owners that both delete the same object, so the copy constructor is deleted (switched off on purpose):

#include <iostream>
#include <string>
#include <memory>
using namespace std;

int main() {
    unique_ptr<string> counter = make_unique<string>("idli order");
    unique_ptr<string> waiter = counter;       // copy the owner?
    cout << *waiter << "\n";
    return 0;
}

Compiler output:

main.cpp: In function 'int main()':
main.cpp:8:33: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = std::__cxx11::basic_string<char>; _Dp = std::default_delete<std::__cxx11::basic_string<char> >]'
    8 |     unique_ptr<string> waiter = counter;       // copy the owner?
      |                                 ^~~~~~~
In file included from /usr/include/c++/13/memory:78,
                 from main.cpp:3:
/usr/include/c++/13/bits/unique_ptr.h:522:7: note: declared here
  522 |       unique_ptr(const unique_ptr&) = delete;
      |       ^~~~~~~~~~

To hand over ownership, use std::move:

#include <iostream>
#include <string>
#include <memory>
using namespace std;

int main() {
    unique_ptr<string> counter = make_unique<string>("idli order");
    unique_ptr<string> waiter = move(counter); // hand it over
    cout << "waiter has: " << *waiter << "\n";
    cout << "counter is " << (counter ? "still an owner" : "empty") << "\n";
    return 0;
}

Output:

waiter has: idli order
counter is empty

A moved-from unique_ptr is guaranteed to be empty (nullptr), and only waiter will delete the string.

shared_ptr: many owners, the last one frees

When an object really has several owners, std::shared_ptr keeps a reference count (how many shared_ptrs own it). Copying adds one, a shared_ptr dying or calling reset() subtracts one, and when the count reaches 0 the object is deleted. use_count() shows the count.

#include <iostream>
#include <string>
#include <memory>
using namespace std;

struct Order {
    string item;
    Order(string s) : item(s) {}
    ~Order() { cout << item << " freed\n"; }
};

int main() {
    shared_ptr<Order> kitchen = make_shared<Order>("masala dosa");
    cout << "owners: " << kitchen.use_count() << "\n";
    {
        shared_ptr<Order> waiter = kitchen;  // a second owner
        cout << "owners: " << kitchen.use_count() << "\n";
    }                                        // waiter is gone
    cout << "owners: " << kitchen.use_count() << "\n";
    kitchen.reset();                         // the last owner lets go
    cout << "end of main\n";
    return 0;
}

Output:

owners: 1
owners: 2
owners: 1
masala dosa freed
end of main

masala dosa freed is printed at reset(), before end of main: the moment the last owner let go.

Cost. unique_ptr: the same size and speed as a raw pointer. shared_ptr: copying is O(1) but updates the count atomically (thread-safe, a little slower), and the object needs a small control block; make_shared puts both in one allocation.

Cost summary

Program Result Cost
return const string& to a local warning, then Segmentation fault (UB)
return string by value TKN-42, TKN-7 O(L), moved or elided
new Seat[3] + delete warning, seat 1 freed, munmap_chunk(): invalid pointer (UB)
new Seat[3] + delete[] 3, 2, 1 freed, done O(n)
raw new with an early return 500 orders leaked O(1) each, memory grows
make_unique 0 leaked O(1) each
shared_ptr copy / reset count 1 → 2 → 1 → freed O(1) per copy

Common mistakes (and the real results)

Mistake What you see Why Fix
return a reference to a local warning: reference to local variable 'token' returned [-Wreturn-local-addr], then a crash or garbage the local dies at return return by value
return a pointer to a local array warning: address of local variable 'marks' returned [-Wreturn-local-addr] same vector<int> by value
new T[n] then delete p warning: ... called on pointer returned from a mismatched allocation function, munmap_chunk(): invalid pointer delete is for one object delete[], or vector
an early return (or exception) before delete no error: memory leaks a raw pointer frees nothing make_unique
copying a unique_ptr error: use of deleted function 'std::unique_ptr<...>::unique_ptr(const std::unique_ptr<...>&)' one owner only std::move
using a pointer after delete warning: pointer used after 'void operator delete(void*, std::size_t)' [-Wuse-after-free], garbage like 1475630857 it dangles smart pointers; set raw pointers to nullptr
deleting a stack variable crash (free(): invalid pointer or similar) it was never from new only delete what new gave you
two shared_ptrs owning each other no error: neither is ever freed a cycle keeps both counts above 0 make one link a weak_ptr

Mini project: a cinema booking system with no delete

Each booking has exactly one owner (unique_ptr in a map), its seats are a vector<int> (no new[]), and every booking co-owns its show with a shared_ptr. When the show is removed from the schedule, it stays alive as long as some booking still refers to it, and is freed automatically when the last booking is cancelled. There is no new and no delete anywhere.

#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <map>
using namespace std;

struct Show {
    string movie;
    explicit Show(string m) : movie(move(m)) { cout << "  [show " << movie << " created]\n"; }
    ~Show() { cout << "  [show " << movie << " freed]\n"; }
};

struct Booking {
    int id;
    shared_ptr<Show> show;               // every booking co-owns its show
    vector<int> seats;                   // the seats: a vector, never new[]
    Booking(int id, shared_ptr<Show> s, vector<int> seats)
        : id(id), show(move(s)), seats(move(seats)) {}
};

int main() {
    map<string, shared_ptr<Show>> schedule;
    schedule["Monsoon"] = make_shared<Show>("Monsoon");
    map<int, unique_ptr<Booking>> bookings;   // each booking has ONE owner

    bookings[1] = make_unique<Booking>(1, schedule["Monsoon"], vector<int>{4, 5, 6});
    bookings[2] = make_unique<Booking>(2, schedule["Monsoon"], vector<int>{9});
    cout << "owners of the show: " << schedule["Monsoon"].use_count() << "\n";

    schedule.erase("Monsoon");            // the show leaves the schedule...
    cout << "removed from schedule; booking 1 still shows "
         << bookings[1]->show->movie << " (owners: " << bookings[1]->show.use_count() << ")\n";

    bookings.erase(1);                   // unique_ptr frees booking 1
    cout << "booking 1 cancelled\n";
    bookings.erase(2);                   // the last owner: the show is freed now
    cout << "booking 2 cancelled\n";
    return 0;
}

Output:

  [show Monsoon created]
owners of the show: 3
removed from schedule; booking 1 still shows Monsoon (owners: 2)
booking 1 cancelled
  [show Monsoon freed]
booking 2 cancelled

Three owners at first: the schedule and two bookings. The show is freed inside bookings.erase(2), before booking 2 cancelled is printed.

Practice questions (with solutions)

1. Your turn: find and fix the bugs.

int* makeMarks(int n) {
    int marks[100];                // up to 100 students
    for (int i = 0; i < n; i++) marks[i] = 50;
    return marks;
}
int main() { int* m = makeMarks(3); cout << m[0]; delete m; }
Solution

-Wall says:

main.cpp:6:12: warning: address of local variable 'marks' returned [-Wreturn-local-addr]

and the program crashes with Segmentation fault. Bugs:

  1. marks is a local array: it dies when makeMarks returns, so m dangles (and g++ even returns a null pointer here, so m[0] crashes).
  2. delete m frees memory that never came from new (and an array would need delete[] anyway).
  3. A hidden third bug: more than 100 students overflow the array.

Fix: return a vector<int> by value. It holds exactly n marks, owns them, and frees itself.

#include <iostream>
#include <vector>
using namespace std;

vector<int> makeMarks(int n) {
    vector<int> marks(n, 50);            // exactly n marks, all 50
    return marks;                        // returned by value (moved)
}

int main() {
    vector<int> m = makeMarks(3);
    cout << m[0] << " (" << m.size() << " students)\n";
    vector<int> big = makeMarks(1000);   // no 100-student limit
    cout << big[999] << " (" << big.size() << " students)\n";
    return 0;
}

Output:

50 (3 students)
50 (1000 students)

2. Count leaks in your own class with a static counter.

Solution

Add static int alive; to the class, alive++ in every constructor (including the copy constructor, if you write one), alive-- in the destructor, and define int ClassName::alive = 0; outside the class. Print it at the end of main: anything above 0 is a leak. This is exactly the Order class above (500 with raw new, 0 with make_unique). Real projects use tools such as AddressSanitizer (-fsanitize=address) or Valgrind to find leaks.

3. Move unique_ptrs into a vector.

Solution
#include <iostream>
#include <memory>
#include <string>
#include <vector>
using namespace std;

int main() {
    vector<unique_ptr<string>> tray;
    auto order = make_unique<string>("vada pav");
    tray.push_back(move(order));         // ownership goes into the vector
    tray.push_back(make_unique<string>("poha"));   // a temporary moves by itself
    cout << "order is " << (order ? "still set" : "empty") << "\n";
    for (const auto& o : tray) cout << *o << "\n";
    return 0;
}

Output:

order is empty
vada pav
poha

push_back(order) without move would be the "use of deleted function" error. A temporary (make_unique<...>(...) written directly) is moved automatically.

4. A shared_ptr cycle, and weak_ptr. Two people who each hold a shared_ptr to the other are never freed. Show it, then fix it.

Solution
#include <iostream>
#include <memory>
#include <string>
using namespace std;

struct Person {
    string name;
    shared_ptr<Person> friendStrong;     // owns the friend
    weak_ptr<Person> friendWeak;         // only watches the friend
    Person(string n) : name(n) {}
    ~Person() { cout << name << " freed\n"; }
};

int main() {
    {
        auto a = make_shared<Person>("Asha");
        auto b = make_shared<Person>("Ravi");
        a->friendStrong = b;
        b->friendStrong = a;             // a cycle of owners
        cout << "strong cycle: a count " << a.use_count() << "\n";
    }
    cout << "--- after the strong block (nobody freed) ---\n";
    {
        auto a = make_shared<Person>("Neha");
        auto b = make_shared<Person>("Priya");
        a->friendWeak = b;
        b->friendWeak = a;               // weak: does not own
        cout << "weak links: a count " << a.use_count() << "\n";
        if (auto f = a->friendWeak.lock()) cout << a->name << "'s friend is " << f->name << "\n";
    }
    cout << "end of main\n";
    return 0;
}

Output:

strong cycle: a count 2
--- after the strong block (nobody freed) ---
weak links: a count 1
Neha's friend is Priya
Priya freed
Neha freed
end of main

Asha and Ravi are never freed: each keeps the other's count at 1. A weak_ptr watches an object without owning it (it does not change use_count); lock() gives a shared_ptr if the object is still alive, or an empty one if it is gone.

Quick quiz

1. What is use_count() at the end? (the episode quiz)

auto a = make_shared<int>(5);
auto b = a;
{
    auto c = b;
}
b.reset();
cout << a.use_count();

(A) 0 (B) 1 (C) 2 (D) 3

Answer

(B) 1. a: 1, b = a: 2, c inside the braces: 3, the braces end: 2, b.reset(): 1. Real output: 1.

2. Is this safe? const int& biggest(const vector<int>& v) { return *max_element(v.begin(), v.end()); }

Answer

Yes, as long as the caller's vector outlives the reference: it refers to an element of the caller's vector, not to a local. It would dangle if called with a temporary, e.g. const int& m = biggest({3, 9, 4}); (the temporary vector dies at the end of that line).

3. What does delete[] do that delete does not?

Answer

It reads the element count stored by new[], runs the destructor of every element (in reverse order), and frees the block from its real start.

4. After auto b = std::move(a); with a a unique_ptr, what is a?

Answer

Guaranteed empty (nullptr); if (a) is false. (For most other standard types, such as string, a moved-from object is only "valid but unspecified": see episode 27.)

5. Which smart pointer for: (a) a vector of shapes the vector alone owns, (b) a texture shared by many sprites, (c) a back-link from a child to its parent?

Answer

(a) unique_ptr, (b) shared_ptr, (c) weak_ptr (or a raw non-owning pointer), so the parent and child do not form an ownership cycle.

Interview questions

  1. What is a dangling reference or pointer? One that refers to an object that has already been destroyed or freed; using it is undefined behaviour.
  2. Why is returning a reference to a local wrong? The local is destroyed when the function returns; the reference outlives it.
  3. Is returning a big object by value slow? No: copy elision (RVO/NRVO) builds it in place, or it is moved.
  4. Stack vs heap? Stack: automatic, freed at the end of the scope, fast, limited size. Heap: new/delete (or a container/smart pointer), lives until freed.
  5. Difference between delete and delete[]? delete destroys one object; delete[] destroys every element of an array made with new[]. Mixing them is UB.
  6. What is a memory leak? Memory allocated and never freed; the program's memory use grows.
  7. What is RAII? Tie a resource to an object's lifetime: acquire it in the constructor, release it in the destructor, so it is released on every path, including exceptions.
  8. unique_ptr vs shared_ptr? unique_ptr: one owner, no overhead, move-only. shared_ptr: shared ownership with a reference count; the last owner deletes.
  9. Why prefer make_unique / make_shared? No naked new, exception-safe, and make_shared allocates the object and the control block together.
  10. Why can't you copy a unique_ptr? Its copy constructor is deleted: two owners would delete the same object twice.
  11. What is a weak_ptr for? A non-owning observer of a shared_ptr object, used to break ownership cycles; lock() checks it is still alive.
  12. How do you find leaks? Count objects, or use AddressSanitizer (-fsanitize=address) / Valgrind.
  13. What is a segmentation fault? The operating system stops a program that reads or writes memory it is not allowed to (e.g. through a null or dangling pointer).

Glossary

Term Meaning Example
Reference Another name for an existing variable; no copy const string& t
Local variable A variable inside a function; destroyed when it returns string token
Lifetime From when an object is created until it is destroyed token dies at return
Dangling reference / pointer Refers to an object that no longer exists the returned token
Undefined behaviour (UB) Code the language gives no meaning to: anything may happen using a dangling reference
Segmentation fault The OS stops a program for an invalid memory access Segmentation fault
endl Writes a newline and flushes the output immediately lines printed before a crash
Return by value The function returns the object itself string makeToken(int)
Copy elision / NRVO The compiler builds the returned object directly in the caller no copy at all
Move Handing over an object's resources instead of copying a string's buffer
Stack Automatic memory for locals, freed at the end of the scope int ticket;
Heap Memory from new, freed with delete new Seat[3]
new / delete Create / destroy one heap object new Order(...)
new[] / delete[] Create / destroy a heap array delete[] row;
Mismatched delete Freeing with the wrong form new[] + delete
munmap_chunk(): invalid pointer The allocator found an address it never gave out the wrong delete
SIGABRT / exit code 134 The program was aborted after invalid pointer
Memory leak Memory taken and never given back 500 orders
Static data member One variable shared by all objects of a class static int alive;
Raw pointer A plain address that owns and frees nothing by itself Order*
Owner The code responsible for freeing an object the unique_ptr
RAII Release a resource in a destructor, so every path releases it unique_ptr, vector
Smart pointer An object that owns heap memory and frees it unique_ptr, shared_ptr
unique_ptr Exactly one owner; move-only make_unique<Order>(...)
Deleted function A function switched off with = delete unique_ptr's copy constructor
std::move Marks an object as "may be moved from" waiter = move(counter)
shared_ptr Shared ownership with a reference count make_shared<Order>(...)
Reference count / use_count() How many shared_ptrs own the object 1 → 2 → 1
reset() Gives up ownership now kitchen.reset();
Control block The hidden record that holds a shared_ptr's count made by make_shared
weak_ptr A non-owning observer; lock() checks it is alive breaking a cycle
Ownership cycle Objects that own each other, so none is freed Asha ↔ Ravi

Summary

  • Never return a reference or pointer to a local: it dangles, and using it is undefined behaviour (here a segmentation fault). Return by value: it is moved or elided, not slowly copied.
  • new pairs with delete, new[] with delete[]. A mismatch is UB (here munmap_chunk(): invalid pointer). Better: vector.
  • A raw pointer frees nothing: an early return or exception leaks. Let an object own the memory (RAII).
  • unique_ptr: one owner, freed on every path, move-only. shared_ptr: many owners, the last one frees; break cycles with weak_ptr.

Next episode: modern C++ questions: a lambda that captures a variable by reference after it is gone, what std::move leaves behind in a string, and the range-for loop that silently copies.