Skip to main content

Overview

OpenCV uses automatic memory management with reference counting for Mat objects. This eliminates most manual memory management while providing efficiency through shallow copying.

Reference Counting

How It Works

Each Mat object has:
  • Header: Small, cheap to copy (~100 bytes)
  • Data block: Large, expensive to copy
  • Reference counter: Tracks how many Mat objects share the data

Shallow vs Deep Copy

Shallow Copy (default):
Deep Copy:

Memory Allocation

Automatic Allocation

Constructor Allocation

UMat and Memory Allocators

MatAllocator

Custom memory allocation through MatAllocator class:

Memory Pools

OpenCV supports buffer pooling for frequent allocations:

Best Practices

Avoid Unnecessary Copies

Return Values

Pre-allocation

Manual Memory Management

External Data

Wrap user-allocated memory:

Release Memory

Memory Continuity

Continuous Storage

ROI and Continuity

Common Pitfalls

Dangling Pointers
Fix: Return a clone or the full image.
Shared Data Modification
Fix: Use B = A.clone() if independent data needed.

Performance Considerations

Pass by Reference

Always pass Mat as const reference to avoid header copies

Use ROI

ROI creates header only, no data copy

Avoid clone()

Use shallow copies when possible

Pre-allocate

Reuse matrices in loops to avoid reallocation

Memory Debugging

See Also