LESSON 02 / LIFETIME

Your pointer outlived its welcome.

The object died. Your pointer kept the address. Very thoughtful. Completely useless.

2 MIN READ + QUIZJump to reality check ↓

The mess

The AI returns a pointer to a local variable. You check that it isn't null. Excellent. You've confirmed the corpse has an address.

Lifetime is how long an object exists. Your hotel room number survives checkout. Your booking doesn't. A pointer is the room number, not a lifetime extension.

int* getAnswer() {
    int answer = 42;
    return &answer; // Forwarding address for a dead local.
}

answer dies when the function returns. Reading through that pointer afterward is undefined behavior: C++ promises no particular result. A successful demo doesn't resurrect anything.

The fix

Return this integer by value. The caller gets a value instead of depending on a dead local.

The same trap catches callbacks that borrow locals and run later. Give the callback data it owns, where appropriate, or otherwise keep its target alive through every use.

Non-null doesn't mean alive. Stop asking a null check to perform a séance.

Ask your AI

When does this target die? Can any returned pointer or delayed callback outlive it? Fix the lifetime and explain why every use stays valid.

Receipts: Object lifetime · Return statements.

THE REALITY CHECK

Did that actually stick?

Three questions. “The AI said so” is not an answer.

1 / 3Read through a returned pointer to a dead local. What happens?
2 / 3A pointer passes a null check. What have you proved?
3 / 3A callback borrows a local and runs after it dies. The fix?

Choose one answer for each question.

KEEP GOING. ALL LESSONS ARE OPEN.Borrowed doesn’t mean immortal. →