Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fmt reads memory past the string width specified #2676

Closed
madscientist opened this issue Dec 26, 2021 · 3 comments
Closed

fmt reads memory past the string width specified #2676

madscientist opened this issue Dec 26, 2021 · 3 comments

Comments

@madscientist
Copy link

When building my code with ASAN I discovered that fmt will read memory past the number of bytes specified by the string width field.

Godbolt: https://godbolt.org/z/cTbKGfT9G

If I replace the string width specifier with just "{}" then construct a std::string_view() instead, it works without reading past memory.

If it's required that a buffer must be nul-terminated even if a length restriction is provided, please make that clear in the documentation.

@vitaut
Copy link
Contributor

vitaut commented Dec 26, 2021

Precision is not suitable for this, clarified in 3014b3d.

@vitaut vitaut closed this as completed Dec 26, 2021
@madscientist
Copy link
Author

That's fine but I'm pretty sure that printf's %s does not read more than width bytes and the string is not required to be nul-terminated. I didn't check to see whether fmt::printf() follows this or not.

Also it's a bit unfortunate from a performance perspective that the entire string needs to be scanned only to print a few characters. I guess string_view helps here, although if you want the full printf %s capability of "write N bytes or stop at the first nul byte if there is one" you'll have to do extra work on your own.

@vitaut
Copy link
Contributor

vitaut commented Dec 26, 2021

As you've already found out a proper (and efficient) way to do this is to use string_view. Precision is not suitable for this because it's not measured in code units. It sort of works in printf but mainly because precision has wrong semantics there and they don't have string views.

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

No branches or pull requests

2 participants