Skip to content

mbstowcs() returns bytes not elements #169

@komh

Description

@komh

Hi/2.

POSIX says in https://pubs.opengroup.org/onlinepubs/9799919799/functions/mbstowcs.html:

Otherwise, mbstowcs() shall return the number of the array elements modified [XSI] (or required if pwcs is null), not including a terminating 0 code, if any. The array shall not be zero-terminated if the value returned is n.

Here is a test code.

#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <locale.h>

int main( void )
{
    const char *s = "한글!";
    wchar_t ws[ 4 ];
    int rc;
    int wlen;
    int errors = 0;
    int failed;

    printf("Testing mbstowcs() returns in wide-characters...\n");

    setlocale( LC_ALL, "ko_KR.CP949");

    rc = mbstowcs( ws, s, sizeof( ws ));
    wlen = wcslen( ws );
    failed = rc != wlen;

    printf("%s: non-NULL: rc = %d(%d)\n",
           failed ? "FAILED" : "PASSED", rc, wlen );

    if( failed )
        errors++;

    rc = mbstowcs( NULL, s, 0 );
    failed = rc != wlen;

    printf("%s: NULL: rc = %d(%d)\n",
           failed ? "FAILED" : "PASSED", rc, wlen );

    if( failed )
        errors++;

    return !!errors;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions