Skip to content

policy: Remove memory leak on exception#1872

Open
jrajahalme wants to merge 1 commit intomainfrom
policy-fix-leak-on-exception
Open

policy: Remove memory leak on exception#1872
jrajahalme wants to merge 1 commit intomainfrom
policy-fix-leak-on-exception

Conversation

@jrajahalme
Copy link
Copy Markdown
Member

@jrajahalme jrajahalme commented Apr 23, 2026

Keep the new map in the stack so that it is not leaked on exception. Move-construct to the heap when exchanging for the old map.

Constructing the new RawPolicyMap on the stack first is both safe and efficient here. It keeps the whole update transactional: while parsing and populating the map, all temporary state remains thread-local and unpublished, so any exception simply unwinds without exposing a partially built policy map to readers. Only once the map is fully ready do we allocate the final heap object and move the finished absl::flat_hash_map into it for atomic publication. That move is efficient: for this flat_hash_map<std::string, std::shared_ptr<...>> type, Abseil’s move constructor transfers ownership of the existing backing table rather than copying or rebuilding the entries, so the extra cost at publication time is essentially just one heap allocation for the map object itself.

Keep the new map in the stack so that it is not leaked on exception.
Move-construct to the heap when exchanging for the old map.

Constructing the new RawPolicyMap on the stack first is both safe and
efficient here. It keeps the whole update transactional: while parsing
and populating the map, all temporary state remains thread-local and
unpublished, so any exception simply unwinds without exposing a partially
built policy map to readers. Only once the map is fully ready do we
allocate the final heap object and move the finished absl::flat_hash_map
into it for atomic publication. That move is efficient: for this
flat_hash_map<std::string, std::shared_ptr<...>> type, Abseil’s move
constructor transfers ownership of the existing backing table rather than
copying or rebuilding the entries, so the extra cost at publication time
is essentially just one heap allocation for the map object itself.

Signed-off-by: Jarno Rajahalme <jarno@isovalent.com>
@jrajahalme jrajahalme requested a review from a team as a code owner April 23, 2026 13:15
@jrajahalme jrajahalme requested a review from nezdolik April 23, 2026 13:15
@jrajahalme jrajahalme added the bug Something isn't working label Apr 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant