This is an automated email from the ASF dual-hosted git repository.

xiaoxiang781216 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/nuttx.git

commit a89aaacc2ce17889d3cf0cb8c096a8c0a12f9b01
Author: liaoao <[email protected]>
AuthorDate: Tue Dec 30 19:34:35 2025 +0800

    libc/stdio: Fix the %p conversion of scanf() on 64-bit systems.
    
    The %p format specifier in sscanf was not properly handling pointer
    sizes on 64-bit systems. Without an explicit length modifier, the
    conversion defaulted to 'unsigned int' (typically 4 bytes), causing
    the upper 32 bits of 64-bit pointers to be truncated.
    
    This patch adds automatic modifier selection based on pointer size
    before processing the %p conversion. The modifier is set according
    to sizeof(void *):
      - 2 bytes -> H_MOD (short)
      - 4 bytes -> NO_MOD (int)
      - 8 bytes -> L_MOD (long) or LL_MOD (long long)
    
    The %p case in the switch statement continues to share the hexadecimal
    parsing logic with %x and %X, but now uses the correct type based on
    the platform's pointer size.
    
    This ensures that sscanf("%p", &ptr) correctly reads the full pointer
    value on both 32-bit and 64-bit architectures.
    
    Signed-off-by: liaoao <[email protected]>
    Signed-off-by: ganjing <[email protected]>
---
 libs/libc/stream/lib_libvscanf.c | 26 ++++++++++++++++++++++++++
 1 file changed, 26 insertions(+)

diff --git a/libs/libc/stream/lib_libvscanf.c b/libs/libc/stream/lib_libvscanf.c
index f4e0971d39e..a574979b9e8 100644
--- a/libs/libc/stream/lib_libvscanf.c
+++ b/libs/libc/stream/lib_libvscanf.c
@@ -571,6 +571,32 @@ static int vscanf_internal(FAR struct lib_instream_s 
*stream, FAR int *lastc,
             {
               bool sign;
 
+              /* A pointer is converted as an unsigned integer of its own
+               * size.  Select the length before the argument is fetched.
+               */
+
+              if (fmt_char(fmt) == 'p')
+                {
+                  if (sizeof(void *) == sizeof(unsigned short))
+                    {
+                      modifier = H_MOD;
+                    }
+                  else if (sizeof(void *) == sizeof(unsigned long))
+                    {
+                      modifier = L_MOD;
+                    }
+#if defined(CONFIG_HAVE_LONG_LONG) && ULLONG_MAX != ULONG_MAX
+                  else if (sizeof(void *) == sizeof(unsigned long long))
+                    {
+                      modifier = LL_MOD;
+                    }
+#endif
+                  else
+                    {
+                      modifier = NO_MOD;
+                    }
+                }
+
               /* Get a pointer to the integer value.  We need to do this even
                * if we have reached the end of the input data in order to
                * update the 'ap' variable.

Reply via email to