Why can a C++ std::shared_ptr<std::FILE> with an fclose deleter misbehave after fopen fails, when std::unique_ptr does not?
answer
- empty is not the same as null
- which destructor checks get()
- what the C library does with null
- construct only after checking
basics
~20 sstd::unique_ptr calls its deleter only for a non-null pointer, but a std::shared_ptr built from a null pointer and a deleter owns that null pointer and calls the deleter with it, so fclose(nullptr) runs, which is undefined behaviour.
solid answer
~40 sThe two destructors are specified differently. `~unique_ptr()` is equivalent to `if (get()) get_deleter()(get());`, so a failed `fopen` stored in it is simply ignored. `shared_ptr(p, d)` makes a non-empty `shared_ptr` that owns `p` and `d` even when `p` is null: `use_count()` is 1, and when the last owner goes, `d(p)` is called. With a plain `fclose` deleter that is `fclose(nullptr)`, undefined behaviour in the C library; the constructor's precondition that `d(p)` is well-defined is violated. Fixes: check the `fopen` result before constructing, give the deleter an `if (f)` guard, or create a `std::unique_ptr` first and move it into the `shared_ptr`: converting a null `unique_ptr` yields an empty `shared_ptr` and never calls the deleter.
code
cpp · 22 lines#include <cstdio>
#include <iostream>
#include <memory>
struct FileCloser {
void operator()(std::FILE* f) const noexcept {
std::cout << "FileCloser called with " << (f ? "a stream" : "nullptr") << '\n';
if (f) std::fclose(f); // the guard that makes a null handle safe
}
};
int main() {
std::FILE* missing = std::fopen("/no/such/dir/scan.raw", "rb"); // returns nullptr
{
std::unique_ptr<std::FILE, FileCloser> u(missing);
std::cout << "unique_ptr going out of scope\n";
} // ~unique_ptr: if (get()) ... -> deleter not called
{
std::shared_ptr<std::FILE> s(missing, FileCloser{});
std::cout << "shared_ptr use_count = " << s.use_count() << '\n';
} // ~shared_ptr: owns nullptr and a deleter -> deleter called
}go deeper
Recall that a failed fopen returns a null pointer and that fclose must never be called with one.
Explain the destructor rules: unique_ptr checks get() before calling its deleter, while a shared_ptr built with a deleter calls it unconditionally.
Distinguish an empty shared_ptr from a null one, and pick a fix that holds at every call site: a null-tolerant deleter or construction through unique_ptr.
Decide whether shared deleters in a codebase must tolerate null by contract, and whether C handles may enter shared ownership other than through a unique_ptr.
## Empty versus null A `std::shared_ptr` has two independent properties that are easy to conflate: - **empty** means it owns nothing: no control block, `use_count() == 0`; - **null** means `get()` returns a null pointer. A default-constructed `shared_ptr` is both. But `std::shared_ptr<std::FILE> s(nullptr_file, FileCloser{});` is **null and not empty**: the constructor `template<class Y, class D> shared_ptr(Y* p, D d)` creates a control block that owns `p` and `d`, and its postcondition is `use_count() == 1 && get() == p`. A separate overload, `shared_ptr(nullptr_t p, D d)`, attaches a deleter to a null pointer explicitly, with the same postcondition. ## What each destructor does | Smart pointer | Destructor behaviour when the stored pointer is null | |---|---| | `std::unique_ptr<T, D>` | equivalent to `if (get()) get_deleter()(get());`, so the deleter is not called | | `std::shared_ptr<T>` built with `(p, d)` | owns `p` and `d`, so the last owner calls `d(p)`, even for a null `p` | | `std::shared_ptr<T>` that is empty | no side effects | `std::unique_ptr::reset` follows the same rule as its destructor: it calls the deleter on the old pointer only if that pointer was not null. ## The failure in the imaging tool A tool that reads raw scans opens each file with `std::fopen` and shares the stream between a decoder and a checksum task: 1. `std::fopen("/no/such/dir/scan.raw", "rb")` fails and returns a null pointer. 2. The code builds `std::shared_ptr<std::FILE> s(f, [](std::FILE* p) { std::fclose(p); });` without checking. 3. The last copy is destroyed, the control block calls the lambda with the null pointer, and `std::fclose(nullptr)` runs. `fclose` requires a valid stream, so this is **undefined behaviour**: some C libraries crash at once, others appear to work. The `shared_ptr` constructor also states, as a precondition, that `d(p)` must have well-defined behaviour; passing a null `p` with a deleter that cannot handle it breaks that contract before the destructor ever runs. The same deleter used with `std::unique_ptr` is harmless, because the null pointer never reaches it. ## Three fixes 1. **Check before constructing.** `if (!f) return error;` and build the `shared_ptr` only from a valid stream. It is the clearest, and it reports the failure where it happened. 2. **Make the deleter null-tolerant.** `if (f) std::fclose(f);` costs one branch and makes the deleter safe for both smart pointers, which matters when one deleter type is shared across a codebase. 3. **Go through `std::unique_ptr`.** Converting a `std::unique_ptr<T, D>` into a `std::shared_ptr<T>` is specified as `shared_ptr()` (empty) when the source is null, and otherwise moves the deleter into the new control block. A null handle therefore produces an empty `shared_ptr` that never calls anything. ## A second trap: allocation failure If allocating the control block throws `std::bad_alloc`, the `shared_ptr(p, d)` constructor calls `d(p)` before letting the exception escape, so the handle is not leaked. That is another reason the deleter must accept every value it can be handed, including null, and must not throw. ## Finding it in an existing codebase The pattern is easy to search for and worth sweeping once: - every `std::shared_ptr` constructed with a raw pointer and a deleter, where the pointer comes from a C function that can return null (`fopen`, `dlopen`, a library's `*_open`); - every deleter that calls a C release function without an `if (p)` guard, since one day it will be used with `shared_ptr`; - every `reset(p, d)` on a `shared_ptr`, which behaves like the constructor and so owns a null `p` too. Do not rely on a crash in testing to find it: what a C library does with a null stream is undefined, so one version may crash at once and another may return an error and appear to work. ## What interviewers listen for The distinction between an **empty** and a **null** `shared_ptr`, the exact destructor rule for `unique_ptr`, and a fix that does not depend on remembering a check at every call site.
- Is a std::shared_ptr built from a null pointer and a deleter considered empty?No. It owns the null pointer and the deleter in a control block, so `use_count()` is 1 and the deleter will be called with the null pointer when the last owner goes. An empty `shared_ptr` is one that owns nothing at all, like a default-constructed one or one converted from a null `std::unique_ptr`.
- Why does converting a null std::unique_ptr<FILE, FileCloser> to std::shared_ptr avoid the problem?The standard specifies that conversion as equivalent to `shared_ptr()` when `r.get()` is null, so no control block is created and the deleter is dropped unused. Only a non-null `unique_ptr` hands its pointer and deleter over with `release()` and `std::move`, so the deleter can only ever see a valid handle.
- A shared_ptr holding a null pointer is always empty
- shared_ptr skips the deleter for a null pointer, like unique_ptr
- fclose(nullptr) is a harmless no-op, just like free(nullptr)
- unique_ptr's deleter must handle null because the destructor always calls it
- use_count() is 0 for a shared_ptr built from a null pointer and deleter