Skip to content

Conversation

sribee8
Copy link
Contributor

@sribee8 sribee8 commented Jul 22, 2025

mbrtowc was not handling null destination correctly

mbrtowc was not handling null destination correctly
@llvmbot llvmbot added the libc label Jul 22, 2025
@sribee8 sribee8 requested a review from uzairnawaz July 22, 2025 21:49
@llvmbot
Copy link
Member

llvmbot commented Jul 22, 2025

@llvm/pr-subscribers-libc

Author: None (sribee8)

Changes

mbrtowc was not handling null destination correctly


Full diff: https://github.com/llvm/llvm-project/pull/150118.diff

2 Files Affected:

  • (modified) libc/src/__support/wchar/mbrtowc.cpp (+2-1)
  • (modified) libc/src/wchar/mbtowc.cpp (+1-4)
diff --git a/libc/src/__support/wchar/mbrtowc.cpp b/libc/src/__support/wchar/mbrtowc.cpp
index 90ba934c42b69..0f730d6e6dbec 100644
--- a/libc/src/__support/wchar/mbrtowc.cpp
+++ b/libc/src/__support/wchar/mbrtowc.cpp
@@ -37,7 +37,8 @@ ErrorOr<size_t> mbrtowc(wchar_t *__restrict pwc, const char *__restrict s,
   }
   auto wc = char_conv.pop_utf32();
   if (wc.has_value()) {
-    *pwc = wc.value();
+    if (pwc != nullptr)
+      *pwc = wc.value();
     // null terminator -> return 0
     if (wc.value() == L'\0')
       return 0;
diff --git a/libc/src/wchar/mbtowc.cpp b/libc/src/wchar/mbtowc.cpp
index eae39ba6081f3..6d099d43da5fa 100644
--- a/libc/src/wchar/mbtowc.cpp
+++ b/libc/src/wchar/mbtowc.cpp
@@ -25,10 +25,7 @@ LLVM_LIBC_FUNCTION(int, mbtowc,
   if (s == nullptr)
     return 0;
   internal::mbstate internal_mbstate;
-  // temp ptr to use if pwc is nullptr
-  wchar_t buf[1];
-  auto ret =
-      internal::mbrtowc(pwc == nullptr ? buf : pwc, s, n, &internal_mbstate);
+  auto ret = internal::mbrtowc(pwc, s, n, &internal_mbstate);
   if (!ret.has_value() || static_cast<int>(ret.value()) == -2) {
     // Encoding failure
     libc_errno = EILSEQ;

Copy link
Contributor

@uzairnawaz uzairnawaz left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, might be worth adding a test for this specific edge case (null dest)

@sribee8 sribee8 merged commit 5edb845 into llvm:main Jul 22, 2025
14 of 19 checks passed
@sribee8 sribee8 deleted the mbtowc-fixes branch July 22, 2025 22:47
mahesh-attarde pushed a commit to mahesh-attarde/llvm-project that referenced this pull request Jul 28, 2025
mbrtowc was not handling null destination correctly

---------

Co-authored-by: Sriya Pratipati <sriyap@google.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants