Skip to content

Do not crash on capitalize with an empty string (#337) - #342

Closed
youdie006 wants to merge 1 commit into
pantor:mainfrom
youdie006:fix/337-capitalize-empty
Closed

youdie006 wants to merge 1 commit into
pantor:mainfrom
youdie006:fix/337-capitalize-empty

Conversation

@youdie006

Copy link
Copy Markdown
Contributor

Fixes #337.

Problem

{{ capitalize("") }} crashes. In Renderer::visit's Op::Capitalize case the code unconditionally writes result[0] and dereferences result.begin() + 1:

auto result = get_arguments<1>(node)[0]->get<json::string_t>();
result[0] = static_cast<char>(::toupper(result[0]));
std::transform(result.begin() + 1, result.end(), result.begin() + 1, ...);

For an empty string result[0] is out of bounds, result.begin() + 1 is an invalid iterator, and the transform range [begin() + 1, end()) is malformed (first > last). This is reachable from ordinary valid template input, so capitalize("") segfaults (a _GLIBCXX_DEBUG build aborts with "function requires a valid iterator range"; ASan reports a stack-buffer-overflow read).

Fix

Guard the capitalization with a non-empty check; an empty argument returns "" (the reporter's expected behavior). Applied to both include/inja/renderer.hpp and the single_include/inja/inja.hpp amalgamation.

Test

Added CHECK(env.render("{{ capitalize(\"\") }}", data) == ""); to the existing capitalize subcase in test/test-functions.cpp. Red-green verified: before the fix the test binary segfaults (exit 139) at this case; after, all 15 test cases / 259 assertions pass, warning-clean under -Wall -Wextra.

The capitalize function wrote result[0] and dereferenced result.begin()+1
unconditionally, so capitalize with an empty string indexed an empty
std::string out of bounds and passed a malformed [begin()+1, end()) range
to std::transform, segfaulting on valid template input.

Guard the transform with a non-empty check; an empty argument now returns
an empty string. Applied to both the modular header and the single-include
amalgamation.

Fixes pantor#337
@pantor

pantor commented Aug 18, 2026

Copy link
Copy Markdown
Owner

Issue was resolved by #343.

@pantor pantor closed this Aug 18, 2026
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.

capitalize("") causes a crash

2 participants