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

Non-null-terminated string with precision in printf #1595

Closed
devinamatthews opened this issue Mar 15, 2020 · 1 comment
Closed

Non-null-terminated string with precision in printf #1595

devinamatthews opened this issue Mar 15, 2020 · 1 comment

Comments

@devinamatthews
Copy link

The man page for printf states, "If a precision is specified, no more bytes than the number specified are written, but no partial multibyte characters are written. Note that the precision determines the number of bytes written, not the number of wide characters or screen positions. The array must contain a terminating null wide character, unless a precision is given and it is so small that the number of bytes written exceeds it before the end of the array is reached." (Emphasis mine).

In arg_formatter_base::write(const char_type*), the string length is unconditionally computed:

auto length = std::char_traits<char_type>::length(value);

I found that changing this to:

size_t length = 0;
while (!std::char_traits<char_type>::eq(value[length], char_type(0))
    && length != specs_->precision) ++length;

fixed the problem, at least in my case. An example usage that leads to this behavior is:

char foo[] = {'H', 'e', 'l', 'l', 'o'};
fmt::printf("%.5s\n", foo);
@vitaut
Copy link
Contributor

vitaut commented Apr 23, 2020

Great catch, thanks! Fixed in 0463665.

@vitaut vitaut closed this as completed Apr 23, 2020
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