Share via


StringCbLength

Other versions of this page are also available for the following:

Windows Mobile Not SupportedWindows Embedded CE Supported

8/27/2008

This function is a replacement for strlen.

It is used to ensure that a string is not larger than a given length, in bytes. If that condition is met, StringCbLength returns the current length of the string in bytes, not including those used for the terminating null character.

Syntax

HRESULT StringCbLength(      
    LPCTSTR psz,
    size_t cbMax,
    size_t *pcb
);

Parameters

  • psz
    [in] Pointer to a buffer containing the string whose length is being checked.
  • cbMax
    [in] The maximum number of bytes allowed in psz, including those used for the terminating null character.

    This value cannot exceed STRSAFE_MAX_CCH * sizeof(TCHAR).

  • pcb
    [out] Pointer to a variable of type size_t containing the number of bytes in psz, excluding those used for the terminating null character.

    This value is valid only if pcb is not null and the function succeeds.

Return Value

This function returns an HRESULT, as opposed to strlen, which returns an integer.

It is strongly recommended that you use the SUCCEEDED and FAILED macros to test the return value of this function.

Value Description

S_OK

The string at psz was not null, and the length of the string (including the terminating null character) is less than or equal to cbMax characters.

STRSAFE_E_INVALID_PARAMETER

The value in psz is NULL, cbMax is larger than STRSAFE_MAX_CCH * sizeof(TCHAR), or psz is longer than cbMax.

Remarks

StringCbLength is an additional tool for proper buffer handling in your code. Poor buffer handling is implicated in many security issues that involve buffer overruns.

StringCbLength can be used in its generic form, or specifically as StringCbLengthA (for ANSI strings) or StringCbLengthW (for Unicode strings). The form to use is determined by your data.

String data type String literal Function

char

"string"

StringCbLengthA

TCHAR

TEXT("string")

StringCbLength

WCHAR

L"string"

StringCbLengthW

Requirements

Header strsafe.h
Library coredll.dll
Windows Embedded CE Windows CE 5.0 and later

See Also

Reference

StringCchLength