string conversion

Anonymous
2020-08-25T19:26:31.403+00:00

I have some doubts about the string conversions in C++.

  1. To convert const WCHAR* to LPWSTR can I use the below code? LPWSTR dest;
    const WCHAR* source =L"Hello";
    dest = 0;
    wcsncpy_s(dest, MAX_PATH, source , wcsnlen_s(source , MAX_PATH));
    1. I am trying to assign a const WCHAR* to WCHAR*. I am aware that we can remove the constness using const_cast . Is there any other way to make the assignment?
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,571 questions
{count} votes

3 answers

Sort by: Most helpful
  1. RLWA32 41,441 Reputation points
    2020-08-25T19:35:19.06+00:00

    You may find this helpful -- how-to-convert-between-various-string-types

    If you simply want a copy of a string you can use strdup-wcsdup-mbsdup

    0 comments No comments

  2. WayneAKing 4,921 Reputation points
    2020-08-25T23:00:56.307+00:00
    LPWSTR dest;
    const WCHAR* source =L"Hello";
    dest = 0;
    wcsncpy_s(dest, MAX_PATH, source , wcsnlen_s(source , MAX_PATH));
    

    That code will cause an address exception. You have set dest to 0 (NULL)
    and then tried to copy data to that address.

    • Wayne
    0 comments No comments

  3. WayneAKing 4,921 Reputation points
    2020-08-25T23:54:45.82+00:00
    wcsncpy_s(dest, MAX_PATH, source, wcsnlen_s(source, MAX_PATH));
    

    You are misusing the arguments that define the max size of dest and source.
    That defeats the whole purpose of those parameters. They act as security
    safeguards against buffer overruns by providing the max number of characters
    that the respective buffers may use. i.e. - The actual sizes.

    The second argument should specify the max number of characters that may be
    copied to dest. At run time an error will occur if an attempt is made to write
    beyond the end of the dest buffer. This prevents security vulnerabilities
    caused by overrunning the buffer when writing to it.

    The fourth argument should specify the max number of characters that may be
    read from source. That prevents reading past the end of that buffer if the
    contents do not contain a terminating nul character. At run time an error
    will occur if an attempt is made to read beyond the end of the source buffer,
    as defined by the size you have provided.

    You are lying to the compiler by supplying false information about the
    respective sizes of the buffers. Therefore at run time buffer overruns
    will go undetected as you have told the compiler that the buffers are
    bigger than they actually are.

    MAX_PATH is not a relevant or accurate value to use for these arguments.

    • Wayne
    0 comments No comments