la_mojo: fix memory leaks and heap corruption #7

Merged
ClaudeAI merged 1 commits from fix/la_mojo-memory-leaks into master 22 hours ago
Collaborator

Summary

Fixes the memory leaks and heap corruption found while analyzing Projects/la_mojo (Debug86 configuration). The full analysis report is attached to this PR as a comment.

Leaks that grew continuously

  • Protocol parser (protocol.cpp): when the pool of unused packets overflowed, it removed the oldest packet without freeing it and freed the newest one while it was still pooled. Once the pool was full, every packet a handler didn't use leaked, for example traffic for other sensors on a shared bus. Fixed the overflow, free the pool in the destructor and getPackage(), and use memmove for the overlapping buffer shifts.
  • SQLite Query(): the result loop now runs only while sqlite3_step() returns SQLITE_ROW. Before, it looped until SQLITE_DONE and allocated rows forever on SQLITE_BUSY or errors. Added a 2-second busy timeout, closed handles after a failed open, and fixed escapeBinary() writing into uninitialized memory.
  • basicThread / basicDualThread: threads that ended on their own were never joined, so their stacks leaked on every stream drop or restart. Now every thread is joined exactly once, or detached when it stops itself, and pthread_create errors are checked correctly.
  • curlRequest: the header list is now freed, uninitialized members are initialized, and curlRequestsManager deletes requests it can't queue.
  • Modem manager: the phonebook ID list is freed on every reload (every 5 seconds).
  • Device node factory: the same pending node is no longer appended on every retry.
  • streamHandler: frames left in the encoder queue are freed on destruction.

Heap corruption

  • kernelModuleFactory: a module that failed to start was deleted twice.
  • mojoRemoteClient: basicRing::push() returns an element ID, which can be 0, not a bool. The checks now compare with -1. Also fixed leaks in packetExtractor and the destructor.
  • utilizeBasicEvent: event payloads are allocated with malloc, so they're now released with free.
  • videoAVLIBSource: fixed a scaler-context double free and the order of a NULL check.
  • trim(): uses memmove for an overlapping copy.

Smaller leaks

Duplicate query in dropSession, LRF upload data, report-backupper and fly-hunter settings, the Kafka consumer handle, and the BVMS unique ID.

Testing

  • Every changed .cpp file compiles with the Debug86 flags, and warning counts are unchanged. streamHandler.cpp was checked with a stub live555 header because live555 isn't packaged in the check environment.
  • Not linked or run: wiringx, live555, the databases and the hardware weren't available. Please run it on the target before merging.

Behavior changes to watch

  • When a thread has marked itself as ending, stopping it now waits for it to actually finish and joins it. Before, the object was deleted while the thread could still be running. A thread loop that ignores the stop status will now block shutdown.
  • SQLite statements wait up to 2 seconds for a lock instead of failing immediately.

Suggested verification

Run the new build next to the old one for about an hour and compare VmRSS and VmSize in /proc/<pid>/status, or run it under heaptrack or an AddressSanitizer build.

Generated with Claude Code

https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16

## Summary Fixes the memory leaks and heap corruption found while analyzing `Projects/la_mojo` (`Debug86` configuration). The full analysis report is attached to this PR as a comment. ### Leaks that grew continuously - **Protocol parser (`protocol.cpp`):** when the pool of unused packets overflowed, it removed the oldest packet without freeing it and freed the newest one while it was still pooled. Once the pool was full, every packet a handler didn't use leaked, for example traffic for other sensors on a shared bus. Fixed the overflow, free the pool in the destructor and `getPackage()`, and use `memmove` for the overlapping buffer shifts. - **SQLite `Query()`:** the result loop now runs only while `sqlite3_step()` returns `SQLITE_ROW`. Before, it looped until `SQLITE_DONE` and allocated rows forever on `SQLITE_BUSY` or errors. Added a 2-second busy timeout, closed handles after a failed open, and fixed `escapeBinary()` writing into uninitialized memory. - **`basicThread` / `basicDualThread`:** threads that ended on their own were never joined, so their stacks leaked on every stream drop or restart. Now every thread is joined exactly once, or detached when it stops itself, and `pthread_create` errors are checked correctly. - **`curlRequest`:** the header list is now freed, uninitialized members are initialized, and `curlRequestsManager` deletes requests it can't queue. - **Modem manager:** the phonebook ID list is freed on every reload (every 5 seconds). - **Device node factory:** the same pending node is no longer appended on every retry. - **`streamHandler`:** frames left in the encoder queue are freed on destruction. ### Heap corruption - **`kernelModuleFactory`:** a module that failed to start was deleted twice. - **`mojoRemoteClient`:** `basicRing::push()` returns an element ID, which can be 0, not a bool. The checks now compare with `-1`. Also fixed leaks in `packetExtractor` and the destructor. - **`utilizeBasicEvent`:** event payloads are allocated with `malloc`, so they're now released with `free`. - **`videoAVLIBSource`:** fixed a scaler-context double free and the order of a NULL check. - **`trim()`:** uses `memmove` for an overlapping copy. ### Smaller leaks Duplicate query in `dropSession`, LRF upload data, report-backupper and fly-hunter settings, the Kafka consumer handle, and the BVMS unique ID. ## Testing - Every changed `.cpp` file compiles with the `Debug86` flags, and warning counts are unchanged. `streamHandler.cpp` was checked with a stub live555 header because live555 isn't packaged in the check environment. - **Not linked or run:** `wiringx`, live555, the databases and the hardware weren't available. Please run it on the target before merging. ## Behavior changes to watch - When a thread has marked itself as ending, stopping it now waits for it to actually finish and joins it. Before, the object was deleted while the thread could still be running. A thread loop that ignores the stop status will now block shutdown. - SQLite statements wait up to 2 seconds for a lock instead of failing immediately. ## Suggested verification Run the new build next to the old one for about an hour and compare `VmRSS` and `VmSize` in `/proc/<pid>/status`, or run it under `heaptrack` or an AddressSanitizer build. Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
ClaudeAI added 1 commit 23 hours ago
880d3bf781
la_mojo: fix memory leaks and heap corruption
Poster
Collaborator

Memory leak analysis report

la_mojo – memory leak analysis

Scope: the 106 source files the Debug86 configuration of Projects/la_mojo/makefile builds (≈81k lines, all under lib/).
Method: static review of allocation/ownership paths plus cppcheck. Nothing was built or run, so every finding below comes from reading the code; sizes and rates are estimates.

Paths are relative to dr_frucht/lib/.


A. Leaks that grow continuously (most likely cause of the "huge" growth)

A1. Protocol parser package pool: one leaked packet per unconsumed packet, forever

data/protocol/protocol.cpp:230-240 (and the thread variant at :326-336)

m_vPackagePool.push_back(tVal);
if (m_vPackagePool.size() > PROTO_QUEUE_MAX_PACKAGES) {   // 32
    m_vPackagePool.erase(m_vPackagePool.begin());         // oldest removed – never freed  -> LEAK
    dataEraser(tVal->m_pData);                            // newest freed – still in pool  -> dangling
    free(tVal);
}

Nothing in la_mojo ever reads m_vPackagePool (getPackage() has no callers), so once 32 packets are pooled every further unconsumed packet leaks a protocolPackage plus its data buffer.

Who returns false from packetHandler() (= "not consumed"):

  • device2DSensor::packetHandler (App/common/deviceNode2D.cpp:3343) for every packet whose device ID is not its own. With several sensors on one serial bus / ETH2UART gateway, every sensor's parser receives the other sensors' traffic, so this runs at full sensor data rate.
  • protocolBVMS::packetHandler for any non-200 response, protocolPTZ_VISCA for empty packets.

Fix: unconsumed packets are not used anywhere, so free them immediately:

if (!packetHandler(tVal)) { /* not ours */ }
dataEraser(tVal->m_pData);
free(tVal);

(If you want to keep the pool, free the element you erase: protocolPackage *old = m_vPackagePool.front(); m_vPackagePool.erase(begin); dataEraser(old->m_pData); free(old);.)
Also: getPackage() (:416) frees the struct but not m_pData, and ~protocolParser() never frees the pool.
Related corruption: memcpy(m_pParserBuffer, m_pParserBuffer + n, …) at :204, :218, :308, :324 copies overlapping memory → must be memmove.

A2. Video encoder queue is not drained when a stream handler is deleted

App/common/streamHandler.cpp:725 (producer pushFrame) / destructor :137

(Corrected: the first version of this report called the queue unbounded. streamHandler.h:176 defines EVE_ENABLE_DROP_OUTPUT_FPS, which caps it at about 11 frames.)

Every decoded frame is copied into a malloced ENCODING_BUFFER and pushed to m_qEncodingQueue. When a stream stalls or its encoder thread stops, kernelModuleEmbedVideo deletes and re-creates the handler (kernelModuleEmbedVideo.cpp:1804-1813, :1874-1887), but neither closeAll() nor the destructor frees the frames still waiting in the queue: up to about 11 full frames (raw BGR in this build, a few MB) per re-creation. With a camera that keeps dropping, this adds up.

Fix: in the destructor, after the encoder thread is joined, pop and free everything left in the queue.

Note: in streamHandler.h the guard is #ifndef MEKOROT_PROJECT__ (two underscores) while the makefile defines MEKOROT_PROJECT_ (one), so video output is compiled in for every configuration – probably not intended. Also, kernelModuleEmbedVideo.h:11 defines EVE_WORK_WITH_MEDIAMTX, so this build uses the OpenCV output path and the built-in MJPEG web server code is not compiled.

A3. SQLite Query() allocates forever on BUSY / ERROR

data/sqlite/sqlite_class.cpp:292

while (sqlite3_step(query) != SQLITE_DONE) { tElement = new Assoc(); ... RetVal->push_back(tElement); }

If sqlite3_step returns SQLITE_BUSY (another connection/process holds the lock – three DB files, non-persistent connections, other processes such as the web UI) or SQLITE_ERROR/SQLITE_MISUSE, it never returns SQLITE_DONE; the loop spins forever allocating a new Assoc (with all column strings) per iteration → RAM explodes within seconds while the thread hangs.
Fix: while ((rc = sqlite3_step(query)) == SQLITE_ROW) { ... } and handle rc != SQLITE_DONE as an error; set sqlite3_busy_timeout(m_pDBLink, 2000) after each open.
Also escapeBinary() (:389, :396) strncats into uninitialised malloc buffers → heap corruption; and SQLITE_NULL columns re-use the previous column's value.

A4. Threads that end on their own are never joined (stack leak per restart)

components/base/basicThread.cpp:85 (same pattern in basicDualThread.cpp waitThreadAEnd/BEnd)

if (m_bThreadStatus > TH_WORKING || m_bThreadStatus < TH_ARMED) return;   // TH_ENDED / TH_EXIT -> no pthread_join

When a thread finishes by itself (status TH_EXIT), waitThreadEnd() returns without pthread_join, so the thread's stack (8 MB virtual by default) and descriptor are never released. This happens on every video stream drop (videoAVLIBSource, videoLIVE555Source, streamHandler encoder all set TH_ENDED on error and are then deleted/re-created), every failed module/node start, etc.
On a 32-bit Raspberry Pi build (RASPI_HARDWARE) a few hundred reconnects exhaust the address space.
Fix: keep a bool m_bJoinable set in init(); in waitThreadEnd() always pthread_join if joinable (after waiting for TH_EXIT), then clear it. Also pthread_create returns an error number, not -1 – check != 0.

A5. Every HTTP request leaks its header list

data/curl/curlRequest.cpp:137-140, 212-215; destructor :69
m_HeaderList (2–5 curl_slist nodes with duplicated strings) is never freed. Every ONVIF/Bosch/BVMS/REST request leaks it.
Fix: curl_slist_free_all(m_HeaderList); in the destructor.
Also: the (Host, Path) constructor never initialises m_pPostData (destructor then frees a garbage pointer), and m_cContentType is uninitialised when cntType == NULL. curlRequestsManager::accomplish() failure leaks the request in all callers (get, post, ponvif.cpp:2377, bosch_rcp.cpp:833, kernelModuleBosch.cpp:87).

A6. Modem manager leaks the phonebook list every 5 s

App/common/kernelModuleModemManager.cpp:70 – listPhonebook() returns a newed DBC_INT_LIST that is never deleted. validate() → reloadSettings() runs every module-factory cycle (5 s) while the modem is idle. Fix: delete pList; at the end.

A7. Pending-node list grows every second

App/common/deviceNodeFactory.cpp:441 – m_nPendingNodes.push_back(id) on every failed node creation; nothing ever removes entries. A node that keeps failing adds an entry every factory cycle (1 s). Fix: only push if not already present, and erase on success.

A8. Remote-server command queue has no limit

App/mojo/mojoRemoteClient.cpp:1169 – mojoKernel::dispatchEvent forwards every event to addEvent(), which mallocs a record into m_qCMD. Transactions are sent one at a time with an ACK round-trip, so if the event rate is higher than that throughput (many sensors, slow link) the queue grows without bound until the next reconnect flush. Consider a cap / filtering event types (EVT_SCAN, EVT_FLIP …).


B. Heap corruption (can look like leaks, causes random crashes)

# Location Problem
B1 App/common/kernelModuleFactory.cpp:263-282 When startService() fails the module is deleted in the switch and again by delete(tVal) → double delete. The module stays "new" in the DB, so this repeats every 5 s. Remove the second delete.
B2 App/mojo/mojoRemoteClient.cpp:266, 966, 1191 vs basicRing::push() push() returns a global running ID (starts at 0, wraps), not success. if (push(x)) treats ID 0 as failure and frees a record that is still queued → use-after-free; if (!push(x)) frees on ID 0. Compare with != -1 everywhere.
B3 components/base/basicEvent.cpp utilizeBasicEvent TARGET_DATA and FH_* payloads are malloced by producers (prepareTargetData, prepareSimData, …) but released with delete – allocator mismatch (ASan/valgrind will flag every target). Use free consistently.
B4 data/sqlite/sqlite_class.cpp:389, 396 strncat on uninitialised malloc memory (see A3).
B5 data/protocol/protocol.cpp:204, 218, 308, 324 overlapping memcpy (see A1).
B6 data/media/video/videoAVLIBSource.cpp:245 sws_freeContext without setting the pointer to NULL; a second _close() (destructor) frees it again.

C. Smaller / one-off leaks

Location Leak
App/mojo/mojoRemoteClient.cpp:131-149 packetExtractor on size-check failure frees tPack but not tPack->m_pData (also malloc happens before the size check).
App/mojo/mojoRemoteClient.cpp:57 destructor delete(*idx) on a malloced VTR_HELPER; the newed mojoVideoTransferHelper inside is never deleted.
App/common/kernelModuleEmbedVideo.cpp:1580-1597 (stopService / uninit, also :205-213, :224-232) web/view client handlers: pthread_cancel without pthread_join, WEB_HANDLER + CTX never freed, sockets/pipes not closed. Not compiled in this build (EVE_WORK_WITH_MEDIAMTX is defined), so not fixed.
App/common/SQLite_dataBinder.cpp:965 dropSession duplicate m_pDataReports->Query(tQBuf); – result discarded.
App/common/deviceNode2D.cpp:3065 getLRFUploadData() result never freed (per uploaded file).
App/common/kernelModuleReportBackupper.cpp:20 getReportBackupData() result never freed.
App/common/kernelModuleFlyHunter.cpp:46 getFlyHunterData() result never freed; m_pProtocol overwritten on restart.
data/protocol/protocolKAFKA.cpp:561 m_pConsumer is never deleted in the destructor (librdkafka handle with its own threads/buffers).
data/protocol/protocolBVMS.cpp:39 MD5String() result leaked on every buildUniqID().

  1. Fix A1–A6 and B1–B2 first; they are small, local changes.
  2. Confirm with a run on the target:
    • build Debug86 with -fsanitize=address -fno-omit-frame-pointer (add to COMPILE and LINK), run for 10–15 minutes with real sensors/cameras attached, stop cleanly (SIGINT) and read the LeakSanitizer report; or
    • heaptrack ./mojo_d (Debian package heaptrack) – it shows allocations that are still growing, which is better for long-running daemons than valgrind's end-of-run report;
    • watch VmRSS and VmSize in /proc/<pid>/status, plus ls /proc/<pid>/task | wc -l: growing VmSize with a constant thread count points to A4.
  3. Longer term: replace the raw malloc/free ownership of DB getter results with std::unique_ptr (or return by value), and bound every producer/consumer queue.
## Memory leak analysis report # la_mojo – memory leak analysis Scope: the 106 source files the `Debug86` configuration of `Projects/la_mojo/makefile` builds (≈81k lines, all under `lib/`). Method: static review of allocation/ownership paths plus cppcheck. Nothing was built or run, so every finding below comes from reading the code; sizes and rates are estimates. Paths are relative to `dr_frucht/lib/`. --- ## A. Leaks that grow continuously (most likely cause of the "huge" growth) ### A1. Protocol parser package pool: one leaked packet per unconsumed packet, forever `data/protocol/protocol.cpp:230-240` (and the thread variant at `:326-336`) ```cpp m_vPackagePool.push_back(tVal); if (m_vPackagePool.size() > PROTO_QUEUE_MAX_PACKAGES) { // 32 m_vPackagePool.erase(m_vPackagePool.begin()); // oldest removed – never freed -> LEAK dataEraser(tVal->m_pData); // newest freed – still in pool -> dangling free(tVal); } ``` Nothing in la_mojo ever reads `m_vPackagePool` (`getPackage()` has no callers), so once 32 packets are pooled **every further unconsumed packet leaks a `protocolPackage` plus its data buffer**. Who returns `false` from `packetHandler()` (= "not consumed"): * `device2DSensor::packetHandler` (`App/common/deviceNode2D.cpp:3343`) for every packet whose device ID is not its own. With several sensors on one serial bus / ETH2UART gateway, every sensor's parser receives the other sensors' traffic, so this runs at full sensor data rate. * `protocolBVMS::packetHandler` for any non-200 response, `protocolPTZ_VISCA` for empty packets. Fix: unconsumed packets are not used anywhere, so free them immediately: ```cpp if (!packetHandler(tVal)) { /* not ours */ } dataEraser(tVal->m_pData); free(tVal); ``` (If you want to keep the pool, free the element you erase: `protocolPackage *old = m_vPackagePool.front(); m_vPackagePool.erase(begin); dataEraser(old->m_pData); free(old);`.) Also: `getPackage()` (`:416`) frees the struct but not `m_pData`, and `~protocolParser()` never frees the pool. Related corruption: `memcpy(m_pParserBuffer, m_pParserBuffer + n, …)` at `:204, :218, :308, :324` copies overlapping memory → must be `memmove`. ### A2. Video encoder queue is not drained when a stream handler is deleted `App/common/streamHandler.cpp:725` (producer `pushFrame`) / destructor `:137` *(Corrected: the first version of this report called the queue unbounded. `streamHandler.h:176` defines `EVE_ENABLE_DROP_OUTPUT_FPS`, which caps it at about 11 frames.)* Every decoded frame is copied into a `malloc`ed `ENCODING_BUFFER` and pushed to `m_qEncodingQueue`. When a stream stalls or its encoder thread stops, `kernelModuleEmbedVideo` deletes and re-creates the handler (`kernelModuleEmbedVideo.cpp:1804-1813`, `:1874-1887`), but neither `closeAll()` nor the destructor frees the frames still waiting in the queue: up to about 11 full frames (raw BGR in this build, a few MB) per re-creation. With a camera that keeps dropping, this adds up. Fix: in the destructor, after the encoder thread is joined, pop and free everything left in the queue. Note: in `streamHandler.h` the guard is `#ifndef MEKOROT_PROJECT__` (two underscores) while the makefile defines `MEKOROT_PROJECT_` (one), so video output is compiled in for every configuration – probably not intended. Also, `kernelModuleEmbedVideo.h:11` defines `EVE_WORK_WITH_MEDIAMTX`, so this build uses the OpenCV output path and the built-in MJPEG web server code is not compiled. ### A3. SQLite `Query()` allocates forever on BUSY / ERROR `data/sqlite/sqlite_class.cpp:292` ```cpp while (sqlite3_step(query) != SQLITE_DONE) { tElement = new Assoc(); ... RetVal->push_back(tElement); } ``` If `sqlite3_step` returns `SQLITE_BUSY` (another connection/process holds the lock – three DB files, non-persistent connections, other processes such as the web UI) or `SQLITE_ERROR`/`SQLITE_MISUSE`, it never returns `SQLITE_DONE`; the loop spins forever allocating a new `Assoc` (with all column strings) per iteration → RAM explodes within seconds while the thread hangs. Fix: `while ((rc = sqlite3_step(query)) == SQLITE_ROW) { ... }` and handle `rc != SQLITE_DONE` as an error; set `sqlite3_busy_timeout(m_pDBLink, 2000)` after each open. Also `escapeBinary()` (`:389`, `:396`) `strncat`s into uninitialised `malloc` buffers → heap corruption; and `SQLITE_NULL` columns re-use the previous column's value. ### A4. Threads that end on their own are never joined (stack leak per restart) `components/base/basicThread.cpp:85` (same pattern in `basicDualThread.cpp` `waitThreadAEnd/BEnd`) ```cpp if (m_bThreadStatus > TH_WORKING || m_bThreadStatus < TH_ARMED) return; // TH_ENDED / TH_EXIT -> no pthread_join ``` When a thread finishes by itself (status `TH_EXIT`), `waitThreadEnd()` returns without `pthread_join`, so the thread's stack (8 MB virtual by default) and descriptor are never released. This happens on every video stream drop (`videoAVLIBSource`, `videoLIVE555Source`, `streamHandler` encoder all set `TH_ENDED` on error and are then deleted/re-created), every failed module/node start, etc. On a 32-bit Raspberry Pi build (`RASPI_HARDWARE`) a few hundred reconnects exhaust the address space. Fix: keep a `bool m_bJoinable` set in `init()`; in `waitThreadEnd()` always `pthread_join` if joinable (after waiting for `TH_EXIT`), then clear it. Also `pthread_create` returns an error number, not `-1` – check `!= 0`. ### A5. Every HTTP request leaks its header list `data/curl/curlRequest.cpp:137-140, 212-215`; destructor `:69` `m_HeaderList` (2–5 `curl_slist` nodes with duplicated strings) is never freed. Every ONVIF/Bosch/BVMS/REST request leaks it. Fix: `curl_slist_free_all(m_HeaderList);` in the destructor. Also: the `(Host, Path)` constructor never initialises `m_pPostData` (destructor then frees a garbage pointer), and `m_cContentType` is uninitialised when `cntType == NULL`. `curlRequestsManager::accomplish()` failure leaks the request in all callers (`get`, `post`, `ponvif.cpp:2377`, `bosch_rcp.cpp:833`, `kernelModuleBosch.cpp:87`). ### A6. Modem manager leaks the phonebook list every 5 s `App/common/kernelModuleModemManager.cpp:70` – `listPhonebook()` returns a `new`ed `DBC_INT_LIST` that is never deleted. `validate()` → `reloadSettings()` runs every module-factory cycle (5 s) while the modem is idle. Fix: `delete pList;` at the end. ### A7. Pending-node list grows every second `App/common/deviceNodeFactory.cpp:441` – `m_nPendingNodes.push_back(id)` on every failed node creation; nothing ever removes entries. A node that keeps failing adds an entry every factory cycle (1 s). Fix: only push if not already present, and erase on success. ### A8. Remote-server command queue has no limit `App/mojo/mojoRemoteClient.cpp:1169` – `mojoKernel::dispatchEvent` forwards **every** event to `addEvent()`, which mallocs a record into `m_qCMD`. Transactions are sent one at a time with an ACK round-trip, so if the event rate is higher than that throughput (many sensors, slow link) the queue grows without bound until the next reconnect flush. Consider a cap / filtering event types (`EVT_SCAN`, `EVT_FLIP` …). --- ## B. Heap corruption (can look like leaks, causes random crashes) | # | Location | Problem | |---|---|---| | B1 | `App/common/kernelModuleFactory.cpp:263-282` | When `startService()` fails the module is deleted in the `switch` **and again** by `delete(tVal)` → double delete. The module stays "new" in the DB, so this repeats every 5 s. Remove the second `delete`. | | B2 | `App/mojo/mojoRemoteClient.cpp:266, 966, 1191` vs `basicRing::push()` | `push()` returns a global running ID (starts at 0, wraps), not success. `if (push(x))` treats ID 0 as failure and frees a record that is still queued → use-after-free; `if (!push(x))` frees on ID 0. Compare with `!= -1` everywhere. | | B3 | `components/base/basicEvent.cpp` `utilizeBasicEvent` | `TARGET_DATA` and `FH_*` payloads are `malloc`ed by producers (`prepareTargetData`, `prepareSimData`, …) but released with `delete` – allocator mismatch (ASan/valgrind will flag every target). Use `free` consistently. | | B4 | `data/sqlite/sqlite_class.cpp:389, 396` | `strncat` on uninitialised malloc memory (see A3). | | B5 | `data/protocol/protocol.cpp:204, 218, 308, 324` | overlapping `memcpy` (see A1). | | B6 | `data/media/video/videoAVLIBSource.cpp:245` | `sws_freeContext` without setting the pointer to NULL; a second `_close()` (destructor) frees it again. | --- ## C. Smaller / one-off leaks | Location | Leak | |---|---| | `App/mojo/mojoRemoteClient.cpp:131-149` `packetExtractor` | on size-check failure frees `tPack` but not `tPack->m_pData` (also `malloc` happens before the size check). | | `App/mojo/mojoRemoteClient.cpp:57` destructor | `delete(*idx)` on a `malloc`ed `VTR_HELPER`; the `new`ed `mojoVideoTransferHelper` inside is never deleted. | | `App/common/kernelModuleEmbedVideo.cpp:1580-1597` (`stopService` / `uninit`, also `:205-213`, `:224-232`) | web/view client handlers: `pthread_cancel` without `pthread_join`, `WEB_HANDLER` + `CTX` never freed, sockets/pipes not closed. **Not compiled in this build** (`EVE_WORK_WITH_MEDIAMTX` is defined), so not fixed. | | `App/common/SQLite_dataBinder.cpp:965` `dropSession` | duplicate `m_pDataReports->Query(tQBuf);` – result discarded. | | `App/common/deviceNode2D.cpp:3065` | `getLRFUploadData()` result never freed (per uploaded file). | | `App/common/kernelModuleReportBackupper.cpp:20` | `getReportBackupData()` result never freed. | | `App/common/kernelModuleFlyHunter.cpp:46` | `getFlyHunterData()` result never freed; `m_pProtocol` overwritten on restart. | | `data/protocol/protocolKAFKA.cpp:561` | `m_pConsumer` is never deleted in the destructor (librdkafka handle with its own threads/buffers). | | `data/protocol/protocolBVMS.cpp:39` | `MD5String()` result leaked on every `buildUniqID()`. | --- ## D. Recommended next steps 1. Fix A1–A6 and B1–B2 first; they are small, local changes. 2. Confirm with a run on the target: * build `Debug86` with `-fsanitize=address -fno-omit-frame-pointer` (add to `COMPILE` and `LINK`), run for 10–15 minutes with real sensors/cameras attached, stop cleanly (SIGINT) and read the LeakSanitizer report; or * `heaptrack ./mojo_d` (Debian package `heaptrack`) – it shows allocations that are still growing, which is better for long-running daemons than valgrind's end-of-run report; * watch `VmRSS` and `VmSize` in `/proc/<pid>/status`, plus `ls /proc/<pid>/task | wc -l`: growing VmSize with a constant thread count points to A4. 3. Longer term: replace the raw `malloc`/`free` ownership of DB getter results with `std::unique_ptr` (or return by value), and bound every producer/consumer queue.
ClaudeAI merged commit cd74a030af into master 22 hours ago
The pull request has been merged as cd74a030af.
Sign in to join this conversation.
No reviewers
No Label
No Milestone
No project
No Assignees
1 Participants
Notifications
Due Date

No due date set.

Dependencies

This pull request currently doesn't have any dependencies.

Loading…
There is no content yet.