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

Throwing printf("%p", "cstring") is problematic #223

Closed
LarsGullik opened this issue Nov 5, 2015 · 2 comments
Closed

Throwing printf("%p", "cstring") is problematic #223

LarsGullik opened this issue Nov 5, 2015 · 2 comments

Comments

@LarsGullik
Copy link

When moving an application from using standard varargs and printf formatting to
cppformat the throwing printf("%p", "cstring") is problematic and a source for bugs.
This since (on most platforms?), standard usage of ("%p", "cstring), will not throw
but just print the pointer value as if an explict cast to void const * where there.

It seems easy to add support for this to cppformat without having un-casted support for
other pointers.

This is the change I did to my local copy of cppformat to make "%s", "cstring" work as
wanted/expected:

diff --git a/platform/cppformat/format.cpp b/platform/cppformat/format.cpp
index 129e6f0..8fa7b96 100644
--- a/platform/cppformat/format.cpp
+++ b/platform/cppformat/format.cpp
@@ -463,13 +463,19 @@ class BasicArgFormatter : public ArgVisitor<Impl, void> {
   }

   void visit_string(Arg::StringValue<char> value) {
-    writer_.write_str(value, spec_);
+    if (spec_.type_ && spec_.type_ == 'p')
+      visit_pointer(value.value);
+    else
+      writer_.write_str(value, spec_);
   }

   using ArgVisitor<Impl, void>::visit_wstring;

   void visit_wstring(Arg::StringValue<Char> value) {
-    writer_.write_str(value, spec_);
+    if (spec_.type_ && spec_.type_ == 'p')
+      visit_pointer(value.value);
+    else
+      writer_.write_str(value, spec_);
   }

   void visit_pointer(const void *value) {
@vitaut
Copy link
Contributor

vitaut commented Nov 8, 2015

Good catch, thanks! You are quite right that printf("%p", "cstring") should work but the fix needs a bit more work to prevent formatting of objects of type std::string as pointers. I'll look into it shortly.

@vitaut
Copy link
Contributor

vitaut commented Nov 9, 2015

Fixed in 8b86a74. Now the following is supported:

  fmt::print("{:p}", "test");
  fmt::printf("%p", "test");

Thanks for reporting.

@vitaut vitaut closed this as completed Nov 9, 2015
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