A program can grab frames from a depth camera all day and still die the moment it finishes: your last log line prints, return 0 executes, and the shell answers with Segmentation fault (core dumped). Nothing in the grab loop is wrong. The fault sits in what C++ destroys after your last statement: first the destructors of your locals, then the namespace-scope and SDK-internal objects. This page is for engineers writing C++ against a camera SDK. You will learn the two teardown windows, test each likely cause, apply a stop-release-destroy sequence that exits clean, and confirm the fix with a ten-run test — including why the crash vanishes under GDB and why the depth stream stays dead until you replug the camera.
Two teardown windows sit after your last line
The marker printed, so your code ran to the end. The crash comes from code you did not write, running in one of two windows:
- Window 1 — the end of main. C++ destroys local objects in the reverse order of their construction. Every destructor you own — frames, Mats, pipeline, context — fires here, after the last statement, before the shell sees the exit code.
- Window 2 — after main returns. Namespace-scope objects, statics and atexit handlers are destroyed, in reverse construction order within each translation unit. Across translation units the order is not guaranteed, and the SDK's own internal statics live in this window too.
Segmentation fault (core dumped) is the shell reporting SIGSEGV: the process touched memory it does not own, and the kernel wrote a core file. A fault in either window is a destructor-time fault. The JPEGs on disk are already correct; the damage happens while the program gives memory back. That is why a clean run that faults after return 0 points at destruction order before anything else.
Likely causes, most probable first
- A cv::Mat that wraps an SDK buffer instead of copying it. The Mat header stores a pointer into memory the SDK owns. When the frame object dies first, the header outlives a freed buffer. See stereo frames saved wrong: copy Mat data from the SDK buffer and wrap an SDK frame buffer in an OpenCV cv::Mat without copying.
- An SDK object at namespace scope. It dies in window 2, after main, against the SDK's own statics in an order the language does not guarantee — the static destruction order problem.
- A stream that was never stopped. If the pipeline destructor has to stop streaming, release the last frame and unregister callbacks in one pass, any slip surfaces as a fault. The camera SDK hangs on exit article covers the same stop-first order for the hang variant.
-
A grab thread still running. A callback or
std::threadtouching frames during teardown dereferences memory you already released. - SDK, driver or firmware mismatch. Least common, and it survives a correct teardown — test it only when 1–4 come up clean.
Work down the list with the tests below instead of guessing.
Worked example: the JPEG grabber that dies after return 0
Inputs, from the reported field case and stripped to its shape: a C++ program grabs one colour frame and one depth frame, colour-maps the depth data into a cv::Mat, writes both to JPEG with cv::imwrite, prints a marker, returns 0. Observed on plain runs: the marker prints, then Segmentation fault (core dumped); the same binary under GDB never faults; after a crash the depth stream stays dead until the camera is replugged or reset. The rule below comes from C++ itself.
Construction order (illustrative names; substitute your SDK's types):
| # | Object | What it is | Borrows from |
|---|---|---|---|
| 1 | ctx |
SDK context: opens the device, owns the driver handles | — |
| 2 | pipe |
SDK pipeline: streams frames through ctx
|
1 |
| 3 |
depth_frame, colour_frame
|
SDK frames: own buffers inside the SDK | 2 |
| 4 | depth_img |
cv::Mat wrapping the mapped depth buffer, no copy |
3 |
| 5 | colour_img |
cv::Mat wrapping the colour buffer, no copy |
3 |
Rule in words: a borrower must be destroyed before the object it borrows from, and C++ destroys locals in reverse construction order — so this declaration order is correct only if the reverse order 5→4→3→2→1 satisfies every borrow.
Arithmetic: check each borrow against the reverse order. colour_img (5) dies before the frames (3). depth_img (4) dies before the frames (3). The frames (3) die before pipe (2). pipe (2) dies before ctx (1). All four borrows hold, so five plain locals of main are already in the correct destruction order.
Result: the bug is not the order of locals — it is an object that escapes the pattern. Three candidates remain: one of the five moved to namespace scope, a Mat kept alive past its frame (cause 1), or a stream still running at teardown (cause 3).
Decision and threshold: fixed means 10 of 10 plain runs exit with no signal, run 11 opens the depth stream without a replug, and one AddressSanitizer build exits with no heap-use-after-free line. Two minutes of evidence come free: gdb ./grab_app core, then bt (enable cores first with ulimit -c unlimited if the shell wrote none; expect a core of a few hundred MB on a process holding a large frame heap, so keep disk space for it). A cv::Mat destructor in the backtrace picks cause 1; the SDK context destructor picks cause 2 or 3.
Test for each cause
-
Wrapped buffer (cause 1): rebuild with every Mat made as a copy —
img = raw.clone()orraw.copyTo(img)at creation — and rerun the ten-run test. Clean exit means the Mat was outliving the frame. -
Namespace-scope object (cause 2): grep your sources for the SDK's context or device type declared outside any function, move each one into
main's scope, rerun. Clean exit means static teardown was the killer. - Stream not stopped (cause 3): add the SDK's stop call before any destructor can run, release the frames, rerun. Clean exit means a destructor was doing teardown work it should never have started.
-
Live thread (cause 4):
join()every grab thread and disconnect every callback before the first teardown step, rerun. The stop your camera grab thread without a segfault at shutdown article shows the shutdown handshake.
Why GDB hides it: a debugger shifts stack and heap layout and changes timing. Freed memory in a typical Linux heap stays mapped and still reads, so a use-after-free faults in one layout and not another. Never take "runs fine under GDB" as a pass. Build once with -fsanitize=address (g++ -std=c++17 -fsanitize=address grab.cpp -o grab), run once, exit once — AddressSanitizer prints heap-use-after-free with the allocating, freeing and using stacks, which ends the guessing. Expect the sanitized build to run roughly 2× slower and use more RAM; one exit run is all it needs.
The fix: a teardown sequence that exits clean
-
Copy, never wrap. Every
cv::Matbuilt from SDK data withclone()orcopyTo()at creation. This one line removes cause 1 outright. - Join the readers. Grab threads joined and callbacks disconnected before anything dies.
- Stop streaming. The SDK's stop call, while the context and pipeline are still alive.
- Release the frames. Let the frame objects reach end of scope so their buffers return to the SDK.
- Borrowers before owners. Pipeline before context; declared in dependency order, reverse construction does it for you.
// Generic names: substitute your SDK's types and calls.
SdkContext ctx; // constructed first: owns the driver handles
SdkPipeline pipe(ctx); // borrows ctx
pipe.start(); // stream on
{
SdkFrame f = pipe.wait_for_frame(); // your SDK's frame type
cv::Mat img = f.data().clone(); // copy at creation, never a wrap
cv::imwrite("frame.jpg", img); // the writer closes before any teardown
} // frames and Mats die here: buffers go home
grab_thread.join(); // no reader left mid-frame
pipe.stop(); // stream off while ctx and pipe are alive
return 0; // pipe and ctx now destruct in reverse order:
// borrower first, owner (driver handles) last
Then run the ten-run test from the worked example: zero signals, and a live stream on the next start. At 1–2 s per run the whole test costs well under a minute; a single crash in the ten still counts as a fail.
Why the depth stream dies until you replug
A process killed by SIGSEGV skips every exit path: no atexit handlers, no static destructors, no SDK cleanup. The camera is left as the crash found it — mid-frame, or with its interface still claimed — and nothing puts it back, because the fault was in your process, not the device. Replugging forces the OS to re-enumerate the camera and clears the stuck state; the vendor's documented hardware reset does the same from inside. Once teardown exits normally, the SDK releases the device itself, and the stream survives into the next run.
When the teardown fix does not land
If the backtrace names a destructor inside the SDK while your locals already die in the right order, three leftovers cover most of the rest: a callback still registered into a dead object, a second process holding the device, or an SDK paired with the wrong driver or firmware generation. Check the version pairing first — the 3D camera header version mismatch article shows the alignment check. A crash during the grabs rather than after return 0 is a different family: start with the camera SDK access violation on close teardown and, for the Windows DLL-unload variant, the vision DLL teardown article. The Python form — a pipeline alive into interpreter shutdown — is covered by the KeyboardInterrupt teardown article. The other teardown failures follow the same two windows; the cameras topic collects them.
Same order on any depth camera
None of this depends on the camera head. Context, pipeline, frames and your Mat copies exist in every depth-camera SDK, and the destruction rule is C++'s, not the vendor's — only the spelling of the stop and release calls changes. If the crash has you rebuilding the station anyway, the shop's 3D sensors cover ToF, structured light and laser profiling, the area scan cameras page filters by interface and shutter, and the camera finder narrows both at once:
- Type
- Depth / ToF camera
Laser profilers and stereo 3D cameras
170 models · from $699.00Teardown checklist
- Ten plain runs, zero signals. One crash in ten means the order is still wrong somewhere.
-
One core read.
gdb your-binary core, thenbt; the named destructor picks the cause. -
One ASan build. Exit once with
-fsanitize=address; anyheap-use-after-freeline at shutdown is the bug. - No SDK object at namespace scope. Grep for the SDK's context or device type outside functions.
-
Every Mat a copy.
clone()orcopyTo()at creation; never a raw wrap kept past its frame. - Join before stop. Grab threads joined and callbacks disconnected before the stream stops.
- Stop before destroy. The stop call runs while the context and pipeline are alive.
- Stream survives. The next run opens the depth stream with no replug.
Questions
Can I ignore the crash if the output files are already correct?
No. The fault fires while the heap is half torn down, so the next allocation, the next run, or a different SDK version can move it into code that corrupts data instead of just crashing. It also leaves the camera in a state that costs a replug, and it fails every automated run. The teardown fix is a few lines; the crash class it removes is not worth carrying.
The camera will not come back even after a replug — what next?
Power-cycle it: unplug, wait 10 s for the supply to drain, replug, then check the OS device list (lsusb on Linux) to confirm it enumerates. If it is still absent, suspect power, cable or hub before code, and use the vendor's documented hardware reset if the camera provides one. A camera needing this every cycle points at a teardown that still dies by signal.
Do Python bindings have the same failure?
Yes, in a reference-counting form. Objects die when the last name goes out of scope, so a module-level pipeline or an exception mid-grab can leave frames alive into interpreter shutdown, where module teardown order is again not guaranteed. Stop the stream in a finally block, delete frame references explicitly, and the same stop-release-destroy sequence applies.
Which object must be destroyed last, and why?
The SDK context — the object that opened the device and owns the driver handles. Everything else borrows from it directly or through the pipeline. Two live contexts are where double-release faults come from: each releases handles the other also claims, so open one, construct everything from it, and let reverse construction order destroy the borrowers before it.
Does the camera model or interface change the teardown order?
No. The order lives on your side of the API: context, pipeline, frames and copies exist in every camera SDK, USB or network attached, and C++ destroys them the same way. What changes between models is only the spelling of the stop and release calls in your SDK's header. The ten-run test and the core backtrace apply unchanged.
