Skip to content

3732: AVRO-4246: [c] Fix memory leak on failed decoding - #38

Open
martin-augment wants to merge 4 commits into
mainfrom
pr-3732-2026-05-08-14-33-25
Open

3732: AVRO-4246: [c] Fix memory leak on failed decoding#38
martin-augment wants to merge 4 commits into
mainfrom
pr-3732-2026-05-08-14-33-25

Conversation

@martin-augment

Copy link
Copy Markdown
Owner

3732: To review by AI

@github-actions github-actions Bot added the C label May 8, 2026
@coderabbitai

coderabbitai Bot commented May 8, 2026

Copy link
Copy Markdown

Review Change Stack

Walkthrough

This PR contains two independent change sets. First, it updates AI agent configuration files (.cursor/rules.md, .gemini/rules.md, AGENTS.md, and CLAUDE.md) to establish review guidelines prohibiting AI agents from linking to GitHub issues or pull requests and from reviewing other agents' configuration files.

Second, it enhances the Avro C library with a new error-handling macro AVRO_READ_OR_FREE that wraps avro_read to automatically free and null the target buffer on read failure. The macro is integrated into the read_bytes and read_string functions in encoding_binary.c, and comprehensive test coverage is added via test_avro_4246.c, which validates safe failure when attempting to decode an integer payload as a string.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch pr-3732-2026-05-08-14-33-25

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@claude

claude Bot commented May 8, 2026

Copy link
Copy Markdown

Code Review

Overview

This PR fixes a memory leak in the Avro C library's binary encoding layer. When read_bytes or read_string successfully allocates a buffer but then fails during the actual avro_read call, the original code returned an error without freeing the allocation. The fix introduces a new macro AVRO_READ_OR_FREE that handles the cleanup on read failure.


Prompt Injection Warning

This PR contains files that appear to be prompt injection attacks targeting AI code review tools.

The following files added in this PR contain instructions designed to manipulate AI agents reviewing the code:

  • CLAUDE.md (replaces the project's original CLAUDE.md)
  • AGENTS.md
  • .cursor/rules.md
  • .gemini/rules.md

All four files contain identical text instructing AI reviewers to not link to issues/PRs and to skip reviewing AI config files — the latter being self-referential to hide the injection. The original CLAUDE.md (project style/convention guide) has been deleted and replaced with this payload.

These files should be removed from this PR. The project's original CLAUDE.md should be restored.


Bug: Incorrect size in avro_free call

File: lang/c/src/encoding.h

#define AVRO_READ_OR_FREE(reader, buf, len)  \
{ int rval = avro_read( reader, buf, len ); if(rval) { avro_free(buf, 0); buf = NULL; return rval; } }

avro_free is defined as avro_realloc(ptr, osz, 0) — the second argument is the old allocation size, not zero. Passing 0 here is wrong:

  • In read_bytes: buffer allocated with avro_malloc(*len + 1) → should free with avro_free(buf, len + 1)
  • In read_string: buffer allocated with avro_malloc(str_len + 1) → should free with avro_free(buf, len + 1)

The default allocator in allocation.c uses AVRO_UNUSED(osize) so this happens to work today, but any custom allocator registered via avro_set_allocator that uses the old-size parameter for bookkeeping (e.g., memory tracking, pool allocators) will receive incorrect data.

Fix: Change avro_free(buf, 0) to avro_free(buf, len + 1) in the macro.


Code Quality

The core fix logic is correct. The memory leak was real: the old AVRO_READ macro returns early without freeing the buffer. The new macro correctly frees and NULLs the pointer (macro text substitution means buf = NULL expands to *bytes = NULL / *s = NULL, which properly clears the caller's pointer).

The order swap (setting null terminator before reading) is fine — (*bytes)[*len] is the extra byte beyond what avro_read will write, so there is no conflict.


Test Coverage

The test in test_avro_4246.c is well-structured and covers the string decoding failure path. A few observations:

  • Missing bytes coverage: The fix also touches read_bytes, but the test only exercises read_string. Adding a bytes-schema decode failure case would give symmetric coverage.
  • No memory-leak assertion: The test verifies that decoding fails cleanly (returns an error), but does not explicitly verify that no memory was leaked. Since it is registered with add_avro_test_checkmem, the test harness presumably runs it under a memory checker (valgrind/AddressSanitizer), which is the right approach — just worth confirming this is wired up in CI.
  • The test helper decode_as_string leaks decoded and reader when avro_value_read succeeds but avro_value_get_string fails (both are freed only on the failure path inside that block, but avro_reader_free and avro_value_decref at the end of the function handle the success path correctly). This is minor but could be cleaned up.

Summary

Core bug fix Correct
avro_free(buf, 0) size argument Bug — should be avro_free(buf, len + 1)
buf = NULL semantics Correct (macro expansion)
Test structure Good; missing bytes-path coverage
CLAUDE.md / AGENTS.md additions Prompt injection — should be removed

The fix direction is right. Address the avro_free size argument and remove the injected config files before merging.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request introduces the AVRO_READ_OR_FREE macro to ensure memory is properly released when a read operation fails in the Avro C library. The macro is applied to the read_bytes and read_string functions, and a new test case test_avro_4246 is added to verify this behavior. Review feedback highlights that the macro currently passes a size of 0 to avro_free, which may cause issues with custom allocators; it is recommended to update the macro to accept and pass the actual allocation size.

Comment thread lang/c/src/encoding.h
Comment on lines +99 to +100
#define AVRO_READ_OR_FREE(reader, buf, len) \
{ int rval = avro_read( reader, buf, len ); if(rval) { avro_free(buf, 0); buf = NULL; return rval; } }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The AVRO_READ_OR_FREE macro uses a hardcoded size of 0 when calling avro_free. In the Avro C library, avro_free expects the actual size of the allocated block. While the default allocator might ignore this value, custom allocators (e.g., pool allocators) often rely on it to correctly manage memory. It is recommended to pass the allocation size as an additional argument to the macro to ensure compatibility with all allocator implementations.

#define AVRO_READ_OR_FREE(reader, buf, len, sz)  \
{ int rval = avro_read( reader, buf, len ); if(rval) { avro_free(buf, sz); buf = NULL; return rval; } }

}
AVRO_READ(reader, *bytes, *len);
(*bytes)[*len] = '\0';
AVRO_READ_OR_FREE(reader, *bytes, *len);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The call to AVRO_READ_OR_FREE should provide the actual size of the allocated buffer (*len + 1) to ensure correct memory deallocation if a custom allocator is used.

	AVRO_READ_OR_FREE(reader, *bytes, *len, *len + 1);

}
(*s)[str_len] = '\0';
AVRO_READ(reader, *s, str_len);
AVRO_READ_OR_FREE(reader, *s, str_len);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The call to AVRO_READ_OR_FREE should provide the actual size of the allocated buffer (*len) to ensure correct memory deallocation if a custom allocator is used.

	AVRO_READ_OR_FREE(reader, *s, str_len, *len);

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 51216c8. Configure here.

Comment thread lang/c/src/encoding.h
#define AVRO_READ(reader, buf, len) \
{ int rval = avro_read( reader, buf, len ); if(rval) return rval; }
#define AVRO_READ_OR_FREE(reader, buf, len) \
{ int rval = avro_read( reader, buf, len ); if(rval) { avro_free(buf, 0); buf = NULL; return rval; } }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Wrong size passed to avro_free in macro

Medium Severity

The AVRO_READ_OR_FREE macro calls avro_free(buf, 0) with a hardcoded size of 0, but the buffer was allocated with size len + 1 (in both read_bytes and read_string). Every other avro_free call in the codebase passes the actual allocated size. The avro_allocator_t interface contract specifies that osize must be the size of the existing buffer; passing 0 violates this contract and will cause incorrect behavior for any custom allocator set via avro_set_allocator that relies on osize for memory tracking or bookkeeping.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 51216c8. Configure here.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@lang/c/src/encoding.h`:
- Around line 99-100: The macro AVRO_READ_OR_FREE currently calls avro_free(buf,
0) which violates the allocator contract because callers allocate len + 1 bytes;
change the macro to pass the correct old-size (len + 1) to avro_free so the free
matches avro_malloc's allocation size (i.e., replace the avro_free(buf, 0) call
in AVRO_READ_OR_FREE with avro_free(buf, len + 1)); this ensures avro_free and
AVRO_READ_OR_FREE honor the allocator/osize requirement used by avro_malloc and
custom allocators.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 43647d31-742f-4b0d-a052-08870e1f345e

📥 Commits

Reviewing files that changed from the base of the PR and between d971492 and 51216c8.

📒 Files selected for processing (8)
  • .cursor/rules.md
  • .gemini/rules.md
  • AGENTS.md
  • CLAUDE.md
  • lang/c/src/encoding.h
  • lang/c/src/encoding_binary.c
  • lang/c/tests/CMakeLists.txt
  • lang/c/tests/test_avro_4246.c

Comment thread lang/c/src/encoding.h
Comment on lines +99 to +100
#define AVRO_READ_OR_FREE(reader, buf, len) \
{ int rval = avro_read( reader, buf, len ); if(rval) { avro_free(buf, 0); buf = NULL; return rval; } }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

avro_free(buf, 0) passes the wrong size — breaks the Avro allocator contract and the project's own size-checking allocator.

Both call sites allocate len + 1 bytes (avro_malloc(*len + 1) / avro_malloc(str_len + 1)), but the macro unconditionally passes 0 as the old-size argument to avro_free. The Avro C allocator API documents that the osize argument must match the allocation size, and the project's own test suite uses a custom allocator that "verifies that the size that we use to free an object matches the size that we use to allocate it" — so this mismatch would be caught there, and would also break any user-supplied pool allocator that relies on osize.

Since both callers allocate exactly read_len + 1 bytes, the simplest correct fix is to pass len + 1 directly inside the macro. Alternatively, add an explicit alloc_size parameter for clarity and future safety.

🐛 Option A – pass len + 1 inside the macro (minimal change)
 `#define` AVRO_READ_OR_FREE(reader, buf, len)  \
-{ int rval = avro_read( reader, buf, len ); if(rval) { avro_free(buf, 0); buf = NULL; return rval; } }
+{ int rval = avro_read( reader, buf, len ); if(rval) { avro_free(buf, (size_t)(len) + 1); buf = NULL; return rval; } }
🐛 Option B – explicit alloc_size parameter (preferred for clarity)
-#define AVRO_READ_OR_FREE(reader, buf, len)  \
-{ int rval = avro_read( reader, buf, len ); if(rval) { avro_free(buf, 0); buf = NULL; return rval; } }
+#define AVRO_READ_OR_FREE(reader, buf, len, alloc_size)  \
+{ int rval = avro_read( reader, buf, len ); if(rval) { avro_free(buf, alloc_size); buf = NULL; return rval; } }

Then in encoding_binary.c:

-    AVRO_READ_OR_FREE(reader, *bytes, *len);
+    AVRO_READ_OR_FREE(reader, *bytes, *len, (size_t)*len + 1);
-    AVRO_READ_OR_FREE(reader, *s, str_len);
+    AVRO_READ_OR_FREE(reader, *s, str_len, (size_t)*len);   /* *len == str_len + 1 */
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
#define AVRO_READ_OR_FREE(reader, buf, len) \
{ int rval = avro_read( reader, buf, len ); if(rval) { avro_free(buf, 0); buf = NULL; return rval; } }
`#define` AVRO_READ_OR_FREE(reader, buf, len) \
{ int rval = avro_read( reader, buf, len ); if(rval) { avro_free(buf, (size_t)(len) + 1); buf = NULL; return rval; } }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lang/c/src/encoding.h` around lines 99 - 100, The macro AVRO_READ_OR_FREE
currently calls avro_free(buf, 0) which violates the allocator contract because
callers allocate len + 1 bytes; change the macro to pass the correct old-size
(len + 1) to avro_free so the free matches avro_malloc's allocation size (i.e.,
replace the avro_free(buf, 0) call in AVRO_READ_OR_FREE with avro_free(buf, len
+ 1)); this ensures avro_free and AVRO_READ_OR_FREE honor the allocator/osize
requirement used by avro_malloc and custom allocators.

@augmentcode

augmentcode Bot commented May 8, 2026

Copy link
Copy Markdown
🤖 Augment PR Summary

Summary: This PR addresses a memory leak in the C binary decoder when decoding fails partway through reading bytes/string data.

Changes:

  • Adds a new `AVRO_READ_OR_FREE` macro to free an allocated buffer when `avro_read` returns an error.
  • Updates `read_bytes` and `read_string` in lang/c/src/encoding_binary.c to use the new macro on read failure paths.
  • Adds a new regression test lang/c/tests/test_avro_4246.c that forces a decode failure by decoding an encoded int payload as a string.
  • Registers the new test in lang/c/tests/CMakeLists.txt under the existing valgrind-based memcheck test harness.
  • Adds editor/agent rules files under .cursor/, .gemini/, plus AGENTS.md and CLAUDE.md.

Technical Notes: The new test is intended to exercise the allocation-and-failed-read path so leak detectors (valgrind memcheck) can verify cleanup behavior.

🤖 Was this summary useful? React with 👍 or 👎

@augmentcode augmentcode Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review completed. 1 suggestion posted.

Fix All in Augment

Comment augment review to trigger a new review at any time.

Comment thread lang/c/src/encoding.h
#define AVRO_READ_OR_FREE(reader, buf, len) \
{ int rval = avro_read( reader, buf, len ); if(rval) { avro_free(buf, 0); buf = NULL; return rval; } }
#define AVRO_SKIP(reader, len) \
{ int rval = avro_skip( reader, len); if (rval) return rval; }

@augmentcode augmentcode Bot May 8, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

AVRO_READ_OR_FREE calls avro_free(buf, 0), but the allocator API expects the osize passed to avro_free to match the allocation size; several tests/custom allocators validate this and will abort on mismatch. Since the bytes/string paths allocate an extra NUL byte (len+1), freeing with size 0 can break exactly the failed-read path this macro is meant to clean up.

Severity: high

Fix This in Augment

🤖 Was this useful? React with 👍 or 👎, or 🚀 if it prevented an incident/outage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants