For example the WideCharToMultiByte [1] function of Win32 handles UTF-16 to UTF-8 conversion. If you pass your destination pointer as NULL, then it purely calculates the number of bytes you'll need in your buffer. Then the main program actually allocates the memory and calls it again with the populated destination pointer.
[1]: https://learn.microsoft.com/en-us/windows/win32/api/stringap...