Skip to content

common_crypto: free the IV copy in AesCryptor - #528

Merged
boyan01 merged 2 commits into
mainfrom
common_crypto/free-iv-copy
Nov 9, 2026
Merged

boyan01 merged 2 commits into
mainfrom
common_crypto/free-iv-copy

Conversation

@YeungKC

@YeungKC YeungKC commented Oct 18, 2026

Copy link
Copy Markdown
Contributor

Summary

The AesCryptor constructor copies the IV to native memory with iv.pointer and did not free the copy. Each AesCryptor leaked the IV. CCCryptorCreate copies the IV, the same as the key, and the key copy is already freed after the call. When CCCryptorCreate fails, the constructor also leaked cryptorRef.

     malloc.free(keyPointer);
+    malloc.free(ivPointer);

     if (status != kCCSuccess) {
+      malloc.free(cryptorRef);
       throw Exception('CCCryptorCreate failed: $status');
     }

Evidence

Create and dispose 1,000,000 AesCryptor instances, then compare RSS (macOS):

  • Before: RSS +24 MB
    After: RSS +9 MB

The difference (about 15 MB) matches 16 bytes per instance. The existing aes_test.dart and hmac_test.dart pass.

Merge Danger

Door: two-way

Blast Radius: small

No API change. The memory is freed after CCCryptorCreate returns. The key copy already uses the same order.

The constructor copied the IV to native memory and did not free it,
so each AesCryptor leaked the IV. CCCryptorCreate copies the IV, the
same as the key, which is already freed after the call. Also free
cryptorRef when CCCryptorCreate fails.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

Both cleanup additions preserve the cryptor’s lifetime and address allocation leaks without introducing blocking issues.

No open issues 🎉

What changed in this PR

Fixes two native-memory leaks in common_crypto’s AesCryptor constructor without changing its public API.

Changes:

  • Frees the temporary IV copy after CCCryptorCreate returns.
  • Frees the output-pointer allocation when cryptor creation fails.
File Description
packages/​common_crypto/​lib/​src/​aes.dart Adds cleanup for temporary native allocations.

Review effort: Balanced

@boyan01
boyan01 merged commit 3ac94b6 into main Nov 9, 2026
7 checks passed
@boyan01
boyan01 deleted the common_crypto/free-iv-copy branch November 9, 2026 07:03
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