You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中Checkmarx检测的Memory Leak与MemoryFree_On_StackVariable漏洞修复咨询

Fixing Checkmarx Detected Memory Leak and MemoryFree_On_StackVariable Issues

I'm fixing vulnerabilities detected by Checkmarx in my project. Below is sample code similar to my current project, which triggers Memory Leak and MemoryFree_On_StackVariable issues. Memory is allocated in the addition function, and freed in main. If I allocate memory for sum in main, these vulnerabilities won't be triggered, but in my actual code, I can't do this because the pointer size depends on other variables determined later.

Sample code:

void addition(int *a, int *b, int** sum) { 
    *sum = new int[2]; //MEMORY LEAK is thrown here 
    if (*sum) { 
        for (int i = 0; i < 2; i++) { 
            cout << "Enter two numbers: " <<endl; 
            cin >> a[i] >> b[i]; 
            (*sum)[i] = a[i] + b[i]; 
            cout << "sum:" << (*sum)[i] << endl; 
        } 
    } 
} 
int main() { 
    int* p1 = NULL; 
    p1=new int[2]; 
    int* p2 = NULL; 
    p2 =new int[2]; 
    int *sum = NULL; //MemoryFree_On_StackVariable is thrown here 
    addition(p1 ,p2, &sum); 
    for (int i = 0; i < 2; i++) { 
        cout << "sum is " << sum[i] << endl; 
    } 
    if (p1) { 
        delete[] p1; 
        p1 = NULL; 
        cout << "p1 is deleted" <<endl; 
    } 
    if (p2) { 
        delete[] p2; 
        p2 = NULL; 
        cout << "p2 is deleted" <<endl; 
    } 
    if (sum != NULL) { 
        delete[] sum; 
        sum = NULL; 
        cout << " sum is deleted" << endl; 
    } 
    return 0; 
}

My questions:

  1. How to fix these vulnerabilities?
  2. Are these Checkmarx detections reasonable?
  3. Must memory allocation and deallocation be done in the same function?

1. Fixing the Vulnerabilities

Let's break down each issue and walk through practical fixes:

Fixing the Memory Leak

Checkmarx flags this because static analysis tools struggle to reliably track cross-function memory ownership—even though you know main frees sum, the tool can't guarantee every caller will do the same. Here are two robust solutions:

  • Use Smart Pointers (Highly Recommended)
    Replace raw pointers with C++ smart pointers like std::unique_ptr or std::shared_ptr to automate memory management. This eliminates manual delete calls entirely, and Checkmarx will recognize the automatic cleanup. Example refactor:

    #include <memory>
    #include <iostream>
    using namespace std;
    
    void addition(int *a, int *b, std::unique_ptr<int[]>& sum) { 
        sum = std::make_unique<int[]>(2); // No manual allocation needed
        for (int i = 0; i < 2; i++) { 
            cout << "Enter two numbers: " <<endl; 
            cin >> a[i] >> b[i]; 
            sum[i] = a[i] + b[i]; 
            cout << "sum:" << sum[i] << endl; 
        } 
    } 
    
    int main() { 
        auto p1 = std::make_unique<int[]>(2);
        auto p2 = std::make_unique<int[]>(2);
        std::unique_ptr<int[]> sum; 
        addition(p1.get(), p2.get(), sum); 
        for (int i = 0; i < 2; i++) { 
            cout << "sum is " << sum[i] << endl; 
        } 
        // No need to manually delete p1, p2, sum—they clean themselves up when they go out of scope
        return 0; 
    }
    
  • Explicit Ownership Enforcement (For Raw Pointers)
    If you must stick with raw pointers, add clear comments documenting that the caller owns the memory allocated by addition and is responsible for freeing it. Also, ensure all error paths (like early returns in addition) don't leave allocated memory hanging. While your current code doesn't have leaks, making ownership explicit can help satisfy Checkmarx's analysis.

Fixing MemoryFree_On_StackVariable

This warning is likely a false positive. You're not deleting a stack variable—you're deleting the heap memory that the stack-allocated pointer sum points to, which is valid C++. Checkmarx probably confuses the pointer's storage location (stack) with the memory it references (heap).

Using smart pointers will resolve this warning immediately, as the tool recognizes that smart pointers safely manage heap memory. If you keep raw pointers, initializing sum to nullptr (instead of the outdated NULL macro) and keeping your existing cleanup logic might help the tool correctly interpret your code.

2. Are the Checkmarx Detections Reasonable?

It's a mixed bag:

  • Memory Leak: The warning is theoretically reasonable. Static analysis tools err on the side of caution—they can't verify every caller of addition will remember to free the memory, so they flag it to prevent potential leaks. In your specific code, it's a false positive, but the tool's caution makes sense for general code safety.
  • MemoryFree_On_StackVariable: This is almost certainly a false positive or misinterpretation. Deleting heap memory via a stack-allocated pointer is standard practice in C++, and there's no actual risk here. The tool's analysis is likely confused by the pointer's storage location.

3. Must Allocation and Deallocation Happen in the Same Function?

No, that's not a requirement at all. It's completely valid to allocate memory in one function and free it in another—this is how many APIs work (e.g., functions that return allocated buffers to callers). The critical rule is to have clear ownership semantics: everyone using the code must know exactly who is responsible for cleaning up the memory.

That said, pairing allocation and deallocation in the same function (using RAII patterns like smart pointers) makes code more maintainable and reduces the risk of leaks. Smart pointers are the modern C++ approach because they enforce ownership automatically, so you don't have to rely on humans remembering to call delete.


内容的提问来源于stack exchange,提问作者Indusha S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:55:00