目录

NativeWindowBuffer API Not Paired

Call OH_NativeWindow_DestroyNativeWindowBuffer() in a timely manner after use to release the native window buffer created via OH_NativeWindow_CreateNativeBufferFromNativeBuffer() or OH_NativeWindow_CreateNativeBufferFromSurfaceBuffer(). Otherwise, the buffer resources cannot be reclaimed, causing memory leaks.

Rule Configuration

// rules.json

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

Example of Correct Code

// Positive example

#include "native_window/external_window.h"
void ProcessBufferFromSurfaceWithDestroy(void *surfaceBuffer) 
{
    OHNativeWindowBuffer *buffer = OH_NativeWindow_CreateNativeWindowBufferFromSurfaceBuffer(surfaceBuffer);
    
    if (buffer == nullptr) {
        return;
    }
    
    // Use the buffer for processing...
    
    // Properly destroy the buffer.
    OH_NativeWindow_DestroyNativeWindowBuffer(buffer);
}
void ProcessBufferFromNativeWithDestroy2(OH_NativeBuffer* nativeBuffer) 
{
    OHNativeWindowBuffer *buffer = OH_NativeWindow_CreateNativeWindowBufferFromNativeBuffer(nativeBuffer);
    
    if (buffer == nullptr) {
        return;
    }
    
    // Use the buffer for processing...
    
    // Properly destroy the buffer.
    OH_NativeWindow_DestroyNativeWindowBuffer(buffer);
}

Example of Incorrect Code

// Negative example

#include "native_window/external_window.h"
void ProcessBufferWithoutDestroy(void *surfaceBuffer) 
{
    // Create a native window buffer from a surface buffer.
    OHNativeWindowBuffer *buffer = OH_NativeWindow_CreateNativeWindowBufferFromSurfaceBuffer(surfaceBuffer);
    
    if (buffer == nullptr) {
        return;
    }
    
    // Use the buffer.
    
    // Not released - memory leak!
}

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