目录

NativeWindowRequestBuffer API Not Paired

Call OH_NativeWindow_NativeWindowFlushBuffer() to submit the buffer after requesting it via OH_NativeWindow_NativeWindowRequestBuffer() to manage the buffer lifecycle. Otherwise, the buffer cannot be reclaimed, causing a memory leak.

Rule Configuration

// rules.json

{
  "rules": {
     "cpp": {
       "ResourceLeak": [
         {
           "ruleId": "NativeWindowRequestBuffer API Not Paired",
           "severity": "error",
           "skip": false
         }
       ]
     }
   }
}

Example of Correct Code

// Positive example

#include "native_window/external_window.h"
void RequestAndFlushBuffer(OHNativeWindow *window) 
{
    OHNativeWindowBuffer *buffer = nullptr;
    int fenceFd = -1;
    
    int ret = OH_NativeWindow_NativeWindowRequestBuffer(window, &buffer, &fenceFd);
    
    if (ret != 0 || buffer == nullptr) {
        return;
    }
    
    // Fill the buffer.
    
    // Properly submit the buffer.
    Region region = {nullptr, 0};  // The entire buffer has been updated.
    OH_NativeWindow_NativeWindowFlushBuffer(window, buffer, fenceFd, region);
}

Example of Incorrect Code

// Negative example

#include "native_window/external_window.h"
void RequestBufferWithoutFlush(OHNativeWindow *window) 
{
    OHNativeWindowBuffer *buffer = nullptr;
    int fenceFd = -1;
    
    // Request a buffer.
    int ret = OH_NativeWindow_NativeWindowRequestBuffer(window, &buffer, &fenceFd);
    
    if (ret != 0 || buffer == nullptr) {
        return;
    }
    
    // Fill the buffer.
    // Unflushed - memory leak!
}

For details about how to configure Code Scanner check rules, see Using codescanner.