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 90b701b3a4166941033db962eb090448194d45dd
Author: anpeiyun <[email protected]>
AuthorDate: Tue Aug 19 20:16:24 2025 +0800

    libc/stdlib: Fix the endptr handling in strtol().
    
    If the subject sequence does not have the expected form, no conversion is 
performed; when endptr is not a null pointer, the value of nptr shall be stored 
in the object pointed to by endptr.
    For example, after calling strtol("  ABC", &endptr, 10);, endptr should 
point to the first space ' ', not to 'A'.
    Refer to: 
https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtol.html
    
    Signed-off-by: anpeiyun <[email protected]>
    Signed-off-by: ganjing <[email protected]>
---
 libs/libc/stdlib/lib_strtol.c | 52 +++++++++++--------------------------------
 1 file changed, 13 insertions(+), 39 deletions(-)

diff --git a/libs/libc/stdlib/lib_strtol.c b/libs/libc/stdlib/lib_strtol.c
index 9e78ae814c1..e1e82d0865f 100644
--- a/libs/libc/stdlib/lib_strtol.c
+++ b/libs/libc/stdlib/lib_strtol.c
@@ -56,12 +56,15 @@
 
 long strtol(FAR const char *nptr, FAR char **endptr, int base)
 {
-  unsigned long accum = 0;
   long retval = 0;
   char sign = 0;
 
   if (nptr)
     {
+      /* Get the unsigned value */
+
+      retval = strtoul(nptr, endptr, base);
+
       /* Skip leading spaces */
 
       lib_skipspace(&nptr);
@@ -74,51 +77,22 @@ long strtol(FAR const char *nptr, FAR char **endptr, int 
base)
           nptr++;
         }
 
-      /* Get the unsigned value */
-
-      accum = strtoul(nptr, endptr, base);
+      /* Check for overflow */
 
-      /* Correct the sign of the result and check for overflow */
-
-      if (sign == '-')
+      if (sign == '-' && retval > 0)
         {
-          const unsigned long limit = ((unsigned long)-(LONG_MIN + 1)) + 1;
-
-          if (accum > limit)
-            {
-              set_errno(ERANGE);
-              retval = LONG_MIN;
-            }
-          else
-            {
-              retval = (accum == limit) ? LONG_MIN : -(long)accum;
-            }
+          set_errno(ERANGE);
+          retval = LONG_MIN;
         }
-      else
+      else if (sign != '-' && retval < 0)
         {
-          if (accum > LONG_MAX)
-            {
-              set_errno(ERANGE);
-              retval = LONG_MAX;
-            }
-          else
-            {
-              retval = accum;
-            }
+          set_errno(ERANGE);
+          retval = LONG_MAX;
         }
     }
-
-  /* Return the final pointer to the unused value */
-
-  if (endptr)
+  else if (endptr)
     {
-      if (sign)
-        {
-          if (*((*endptr) - 1) == sign)
-            {
-              (*endptr)--;
-            }
-        }
+      *endptr = NULL;
     }
 
   return retval;

Reply via email to