Skip to content

Disallow constructing pbf_reader from a temporary std::string - #172

Open
kkaefer wants to merge 1 commit into
masterfrom
kk/reader-from-temporary-string
Open

kkaefer wants to merge 1 commit into
masterfrom
kk/reader-from-temporary-string

Conversation

@kkaefer

@kkaefer kkaefer commented Nov 18, 2026

Copy link
Copy Markdown
Member

pbf_reader only stores a pointer into the std::string it is constructed from. Constructing it from a temporary string compiled fine, but the reader pointed to freed memory as soon as the temporary was destroyed:

protozero::pbf_reader message{read_file("data.pbf")}; // dangles
while (message.next()) { ... }                         // use after free

The same happened with pbf_message, since it forwards all constructor arguments to pbf_reader.

This PR contains the following changes:

  • pbf_reader(const std::string&&) is now deleted. It also catches non-const temporaries, since they prefer binding to const std::string&& over const std::string&.
  • The forwarding constructor of pbf_message is now only enabled if pbf_reader is constructible from the arguments. Previously, std::is_constructible reported true for any arguments, and errors only showed up when the constructor body was instantiated.
  • static_asserts in test_basic.cpp that check both classes can be constructed from a std::string lvalue, but not from a temporary.

The reader only stores a pointer into the string, which dangles once the temporary is destroyed. pbf_message's forwarding constructor is now constrained so it inherits this.
@kkaefer
kkaefer requested a review from a team as a code owner November 18, 2026 13:35
@kkaefer
kkaefer requested a review from joto November 18, 2026 13:43
@kkaefer

kkaefer commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

(@joto FYI, in preparation for a 1.9 release of protozero, I'm continuing the theme of small-ish code and documentation fixes that make it harder to misuse the protozero API, and fix subtle bugs that occur once you use protozero to create/parse billions of protobuf files)

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.

1 participant