2 out of 3 rated this helpful - Rate this topic

StringCchLength function

Applies to: desktop apps | Metro style apps

Determines whether a string exceeds the specified length, in characters.

StringCchLength is a replacement for the following functions:

Syntax

HRESULT StringCchLength(
  __in   LPCTSTR psz,
  __in   size_t cchMax,
  __out  size_t *pcch
);

Parameters

psz [in]

Type: LPCTSTR

The string whose length is to be checked.

cchMax [in]

Type: size_t

The maximum number of characters allowed in psz, including the terminating null character. This value cannot exceed STRSAFE_MAX_CCH.

pcch [out]

Type: size_t*

The number of characters in psz, not including the terminating null character. This value is valid only if pcch is not NULL and the function succeeds.

Return value

Type: HRESULT

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

Return codeDescription
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 cchMax characters.

STRSAFE_E_INVALID_PARAMETER

The value in psz is NULL, cchMax is larger than STRSAFE_MAX_CCH, or psz is longer than cchMax.

 

Note that this function returns an HRESULT value, unlike the functions that it replaces.

Remarks

Compared to the functions it replaces, StringCchLength is an additional tool for proper buffer handling in your code. Poor buffer handling is implicated in many security issues that involve buffer overruns.

StringCchLength can be used in its generic form, or in its more specific forms. The data type of the string determines the form of this function that you should use.

String Data TypeString LiteralFunction
char"string"StringCchLengthA
TCHARTEXT("string")StringCchLength
WCHARL"string"StringCchLengthW

 

Requirements

Minimum supported client

Windows XP with SP2

Minimum supported server

Windows Server 2003 with SP1

Header

Strsafe.h

Unicode and ANSI names

StringCchLengthW (Unicode) and StringCchLengthA (ANSI)

See also

StringCbLength

 

 

Send comments about this topic to Microsoft

Build date: 2/3/2012

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
x64 support of string length methods
I thought that this method has no restrictions in length as it uses size_t for input/output. But if found out:
#define STRSAFE_MAX_CCH     2147483647  // max buffer size, in characters, that we support (same as INT_MAX)

So is there any strlen replacement that can handle strings that are longer than INT_MAX ?
Only use this function for untrusted input, us other functions when trusted
This API exists for verifying strings passed by untrusted callers. Most situations don't require the use of this function and will be simpler if the other string lenght functions are used.