Skip to content

fix: add null pointer checks after malloc calls - #33

Merged
deepin-bot[bot] merged 1 commit into
linuxdeepin:masterfrom
mhduiy:cppcheck
Nov 25, 2025
Merged

deepin-bot[bot] merged 1 commit into
linuxdeepin:masterfrom
mhduiy:cppcheck

Conversation

@mhduiy

@mhduiy mhduiy commented Nov 25, 2025 •

Copy link
Copy Markdown
Contributor

Added null pointer checks after malloc calls in three locations to prevent potential segmentation faults and improve error handling. When malloc fails to allocate memory, the code now logs an appropriate error message and returns early instead of proceeding with null pointers.

  1. Added check for check_context.conflic_mac allocation in ipwd_analyse function
  2. Added check for newdevinfo allocation in ipwd_analyse function
  3. Added check for ipconflict_dev_info allocation in ipwd_read_config function

Influence:

  1. Test memory allocation failure scenarios to verify error messages are logged correctly
  2. Verify that null pointer checks prevent crashes when malloc fails
  3. Test normal operation to ensure memory allocation still works correctly
  4. Check error handling behavior when system is under memory pressure

fix: 为malloc调用添加空指针检查

在三个位置为malloc调用添加了空指针检查,以防止潜在的段错误并改进错误处
理。当malloc分配内存失败时,代码现在会记录适当的错误消息并提前返回,而不
是继续使用空指针。

  1. 在ipwd_analyse函数中添加了对check_context.conflic_mac分配的检查
  2. 在ipwd_analyse函数中添加了对newdevinfo分配的检查
  3. 在ipwd_read_config函数中添加了对ipconflict_dev_info分配的检查

Influence:

  1. 测试内存分配失败场景,验证错误消息是否正确记录
  2. 验证当malloc失败时空指针检查是否能防止崩溃
  3. 测试正常操作以确保内存分配仍然正常工作
  4. 检查系统内存压力下的错误处理行为

Summary by Sourcery

Add defensive handling for memory allocation failures in the IP watch daemon to avoid crashes and improve error reporting.

Bug Fixes:

  • Prevent potential crashes in ipwd_analyse by checking malloc results before using allocated buffers for conflict MAC data and new device info.
  • Prevent failures during configuration loading by validating ipconflict_dev_info allocation and returning an error when memory cannot be allocated.

@sourcery-ai

sourcery-ai Bot commented Nov 25, 2025

Copy link
Copy Markdown
Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Adds null checks and error handling after malloc calls in ipwatchd’s analyse and config paths to avoid dereferencing null pointers and improve behavior under low-memory conditions.

Flow diagram for malloc error handling in ipwd_analyse conflic_mac allocation

flowchart TD
    Start["ipwd_analyse entry (conflict detection path)"] --> CheckConflict["Is IP conflict detected and rcv_smac present?"]
    CheckConflict -->|No| End["Return or continue normal processing"]
    CheckConflict -->|Yes| LogInfo["Log IP conflict info with ipwd_message IPWD_MSG_TYPE_INFO"]
    LogInfo --> MallocConflicMac["Allocate check_context.conflic_mac with malloc"]
    MallocConflicMac --> CheckConflicMacNull{Is check_context.conflic_mac NULL?}
    CheckConflicMacNull -->|Yes| LogConflicMacError["Log error with ipwd_message IPWD_MSG_TYPE_ERROR (malloc failed for conflic_mac)"]
    LogConflicMacError --> EarlyReturn["Return early from ipwd_analyse"]
    CheckConflicMacNull -->|No| CopySmac["memcpy rcv_smac into check_context.conflic_mac"]
    CopySmac --> ContinueProcessing["Continue normal packet analysis"]
    EarlyReturn --> FunctionExit["ipwd_analyse exit"]
    ContinueProcessing --> FunctionExit
Loading

Flow diagram for malloc error handling in ipwd_analyse newdevinfo allocation

flowchart TD
    Start["ipwd_analyse entry (device list processing path)"] --> ForEachDevice["Iterate over devices.dev array"]
    ForEachDevice --> CheckExist["For current device, check exist flag"]
    CheckExist -->|exist != 0| NextDevice["Skip allocation and check next device"]
    CheckExist -->|exist == 0| MallocNewDevInfo["Allocate IPCONFLICT_DEV_INFO *newdevinfo with malloc"]
    MallocNewDevInfo --> CheckNewDevInfoNull{Is newdevinfo NULL?}
    CheckNewDevInfoNull -->|Yes| LogNewDevInfoError["Log error with ipwd_message IPWD_MSG_TYPE_ERROR (malloc failed for IPCONFLICT_DEV_INFO)"]
    LogNewDevInfoError --> BreakLoop["Break out of device loop"]
    CheckNewDevInfoNull -->|No| CopyIp["memcpy newdevinfo->ip from devices.dev[i].ip"]
    CopyIp --> CopyMac["memcpy newdevinfo->mac from devices.dev[i].mac"]
    CopyMac --> CopyRemoteMac["memcpy newdevinfo->remote_mac from rcv_smac"]
    CopyRemoteMac --> LinkIntoList["Link newdevinfo into IP conflict info structure or list"]
    LinkIntoList --> NextDevice
    NextDevice -->|More devices| ForEachDevice
    NextDevice -->|No more devices| FunctionExit["ipwd_analyse exit"]
    BreakLoop --> FunctionExit
Loading

Flow diagram for malloc error handling in ipwd_read_config ipconflict_dev_info allocation

flowchart TD
    Start["ipwd_read_config entry"] --> InitDevices["Initialize devices.dev and set devices.devnum = 0"]
    InitDevices --> MallocIpConflict["Allocate ipconflict_dev_info with malloc sizeof(IPCONFLICT_DEV_INFO)"]
    MallocIpConflict --> CheckIpConflictNull{Is ipconflict_dev_info NULL?}
    CheckIpConflictNull -->|Yes| LogIpConflictError["Log error with ipwd_message IPWD_MSG_TYPE_ERROR (malloc failed for ipconflict_dev_info)"]
    LogIpConflictError --> ReturnError["Return IPWD_RV_ERROR from ipwd_read_config"]
    CheckIpConflictNull -->|No| MemsetIp["memset ipconflict_dev_info->ip to 0"]
    MemsetIp --> MemsetMac["memset ipconflict_dev_info->mac to 0"]
    MemsetMac --> MemsetRemoteMac["memset ipconflict_dev_info->remote_mac to 0"]
    MemsetRemoteMac --> ContinueConfig["Continue reading and parsing configuration file"]
    ContinueConfig --> ReturnStatus["Return success or other status from ipwd_read_config"]
    ReturnError --> FunctionExit["ipwd_read_config exit"]
    ReturnStatus --> FunctionExit
Loading

File-Level Changes

Change Details Files
Add null-check and early return for conflic_mac allocation in ipwd_analyse to prevent using a null pointer when logging IP conflicts.
  • After allocating memory for the conflict MAC address, check if the returned pointer is NULL.
  • If allocation fails, log an IPWD_MSG_TYPE_ERROR with a clear message about conflic_mac allocation failure.
  • Return early from ipwd_analyse to avoid subsequent memcpy on a null pointer.
src/plugin-sdbus/plugin-ipwatchd/analyse.c
Guard IPCONFLICT_DEV_INFO allocation with a null check in ipwd_analyse to avoid crashes when building new device info entries.
  • After allocating IPCONFLICT_DEV_INFO, verify the pointer is not NULL before use.
  • On allocation failure, log an error with IPWD_MSG_TYPE_ERROR describing the IPCONFLICT_DEV_INFO malloc failure.
  • Break out of the current processing branch to avoid writing into an invalid structure.
src/plugin-sdbus/plugin-ipwatchd/analyse.c
Add null-check and error-path return for ipconflict_dev_info allocation in ipwd_read_config to ensure config initialization fails cleanly on OOM.
  • After allocating ipconflict_dev_info, check for NULL to detect malloc failure.
  • If allocation fails, log an IPWD_MSG_TYPE_ERROR with a specific message about ipconflict_dev_info allocation.
  • Return IPWD_RV_ERROR instead of proceeding to memset fields on a null pointer.
src/plugin-sdbus/plugin-ipwatchd/config.c

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes - here's some feedback:

  • In ipwd_analyse, the early return after check_context.conflic_mac malloc failure may skip any cleanup or state-reset that this function is expected to perform for the current packet; consider routing failures through a single exit path that handles any required cleanup and keeps check_context/devices state consistent.
  • The three malloc error paths use slightly different control-flow responses (return, break, return value) and hard-coded messages; consider standardizing the error-handling pattern and centralizing the error message format to make future changes and debugging easier.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In ipwd_analyse, the early return after check_context.conflic_mac malloc failure may skip any cleanup or state-reset that this function is expected to perform for the current packet; consider routing failures through a single exit path that handles any required cleanup and keeps check_context/devices state consistent.
- The three malloc error paths use slightly different control-flow responses (return, break, return value) and hard-coded messages; consider standardizing the error-handling pattern and centralizing the error message format to make future changes and debugging easier.

## Individual Comments

### Comment 1
<location> `src/plugin-sdbus/plugin-ipwatchd/analyse.c:261-265` </location>
<code_context>
                 if (exist == 0)
                 {
                     IPCONFLICT_DEV_INFO *newdevinfo = (IPCONFLICT_DEV_INFO *)malloc(sizeof(IPCONFLICT_DEV_INFO));
+                    if (newdevinfo == NULL) {
+                        ipwd_message (IPWD_MSG_TYPE_ERROR, "Unable to allocate memory for IPCONFLICT_DEV_INFO - malloc failed");
+                        break;
+                    }
                     memcpy (newdevinfo->ip, devices.dev[i].ip, IPWD_MAX_DEVICE_ADDRESS_LEN);
</code_context>

<issue_to_address>
**suggestion (bug_risk):** Breaking out of the loop on allocation failure may silently skip processing remaining devices.

When `newdevinfo == NULL`, you log an error and `break`, which prevents processing any remaining devices in this call while still returning as if processing largely succeeded. If an allocation failure should be fatal, consider returning an error or otherwise aborting the whole operation; if not, use `continue` so other devices are still checked for conflicts.

```suggestion
                    IPCONFLICT_DEV_INFO *newdevinfo = (IPCONFLICT_DEV_INFO *)malloc(sizeof(IPCONFLICT_DEV_INFO));
                    if (newdevinfo == NULL) {
                        ipwd_message (IPWD_MSG_TYPE_ERROR, "Unable to allocate memory for IPCONFLICT_DEV_INFO - malloc failed");
                        return;
                    }
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread src/plugin-sdbus/plugin-ipwatchd/analyse.c
Added null pointer checks after malloc calls in three locations to
prevent potential segmentation faults and improve error handling. When
malloc fails to allocate memory, the code now logs an appropriate error
message and returns early instead of proceeding with null pointers.

1. Added check for check_context.conflic_mac allocation in ipwd_analyse
function
2. Added check for newdevinfo allocation in ipwd_analyse function
3. Added check for ipconflict_dev_info allocation in ipwd_read_config
function

Influence:
1. Test memory allocation failure scenarios to verify error messages are
logged correctly
2. Verify that null pointer checks prevent crashes when malloc fails
3. Test normal operation to ensure memory allocation still works
correctly
4. Check error handling behavior when system is under memory pressure

fix: 为malloc调用添加空指针检查

在三个位置为malloc调用添加了空指针检查,以防止潜在的段错误并改进错误处
理。当malloc分配内存失败时,代码现在会记录适当的错误消息并提前返回,而不
是继续使用空指针。

1. 在ipwd_analyse函数中添加了对check_context.conflic_mac分配的检查
2. 在ipwd_analyse函数中添加了对newdevinfo分配的检查
3. 在ipwd_read_config函数中添加了对ipconflict_dev_info分配的检查

Influence:
1. 测试内存分配失败场景,验证错误消息是否正确记录
2. 验证当malloc失败时空指针检查是否能防止崩溃
3. 测试正常操作以确保内存分配仍然正常工作
4. 检查系统内存压力下的错误处理行为
@deepin-ci-robot

Copy link
Copy Markdown

deepin pr auto review

我来对这段代码进行审查和分析:

  1. 内存分配安全性改进:
    优点:
  • 在所有malloc()调用后添加了NULL检查,这是一个很好的安全实践
  • 在内存分配失败时提供了清晰的错误日志
  • 在内存分配失败时进行了适当的错误处理(返回或退出)

建议:

  • 可以考虑使用calloc()替代malloc(),因为:
    1. calloc会自动将内存清零,可以省去后续的memset操作
    2. 更安全,避免使用未初始化的内存
  1. 代码质量改进:
    优点:
  • 错误信息清晰且有意义
  • 代码格式规范
  • 变量命名清晰

建议:

  • 可以将IPWD_MAX_DEVICE_ADDRESS_LEN定义为常量,避免魔法数字
  • 考虑创建一个统一的内存分配错误处理函数,减少重复代码
  1. 性能方面:
  • 目前的改进主要关注安全性,对性能影响不大
  • 使用calloc可能比malloc+memset略慢,但差异很小,安全性更重要
  1. 具体改进建议:
// 定义统一的内存分配错误处理函数
static void* safe_malloc(size_t size, const char* error_msg) {
    void* ptr = malloc(size);
    if (ptr == NULL) {
        ipwd_message(IPWD_MSG_TYPE_ERROR, "%s - malloc failed", error_msg);
        return NULL;
    }
    return ptr;
}

// 使用示例
check_context.conflic_mac = safe_malloc(IPWD_MAX_DEVICE_ADDRESS_LEN, 
                                      "Unable to allocate memory for conflic_mac");
if (check_context.conflic_mac == NULL) {
    return;
}

// 或者使用calloc
check_context.conflic_mac = calloc(1, IPWD_MAX_DEVICE_ADDRESS_LEN);
if (check_context.conflic_mac == NULL) {
    ipwd_message(IPWD_MSG_TYPE_ERROR, 
                "Unable to allocate memory for conflic_mac - calloc failed");
    return;
}
  1. 其他建议:
  • 考虑添加内存使用统计或限制
  • 在程序退出时确保所有分配的内存都被正确释放
  • 可以考虑使用内存池来管理频繁分配的内存

总的来说,这次改进主要提升了代码的安全性,通过添加内存分配失败的检查和处理,使程序更加健壮。建议继续完善错误处理机制,并考虑代码的复用性。

@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: mhduiy, yixinshark

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@mhduiy

mhduiy commented Nov 25, 2025

Copy link
Copy Markdown
Contributor Author

/forcemerge

@deepin-bot

deepin-bot Bot commented Nov 25, 2025

Copy link
Copy Markdown

This pr force merged! (status: blocked)

@deepin-bot
deepin-bot Bot merged commit 6e85b75 into linuxdeepin:master Nov 25, 2025
7 of 8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants