2

Should I make room to it, like this:

 len = MAX_PATH * sizeof(_TCHAR) + sizeof(_TCHAR);

or is:

len = MAX_PATH + sizeof(_TCHAR);

Right size to hold a path including unicode?

Jack
  • 16,276
  • 55
  • 159
  • 284

3 Answers3

10

MAX_PATH (which is always 260) is expressed in characters, not in bytes.

Use the first one when allocating raw memory that is expressed in byte sizes, eg:

LPTSTR path = (LPTSTR) LocalAlloc(LMEM_FIXED, (MAX_PATH + 1) * sizeof(TCHAR));

Use the second one when allocating memory that is expressed in characters, eg:

TCHAR path[MAX_PATH + 1];

LPTSTR path = new TCHAR[MAX_PATH +1];
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 5
    Just for reference, it's enough to allocate `MAX_PATH` characters, e.g. `TCHAR szPath[MAX_PATH];`. The NUL character is already included in the number; see the [MSDN page on naming files](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx) – MicroVirus Sep 13 '15 at 15:04
3

MAX_PATH is defined as 260 in Windef.h irrespective of Unicode.

First approach is fine if you are holding number of bytes. Second approach does not make any sense. If you are holding number of characters, you should use MAX_PATH+1.

doptimusprime
  • 9,115
  • 6
  • 52
  • 90
2

The MAX_PATH macro definition (260 bytes) is an adopted ANSI standard. Unfortunately, this standard was developed long before the advent of the 32-bit OS.

Currently, Unicode versions of the (Windows) file libraries support a path up to 32,767 bytes. However, the MAX_PATH definition remains as it was for (16-bit) MS-DOS

Mahonri Moriancumer
  • 5,993
  • 2
  • 18
  • 28
  • So newly application shouldn't use it? Also, does it means which the following cod from http://msdn.microsoft.com/en-us/library/aa365200%28v=vs.85%29.aspx might fail in new Windows versions? – Jack May 04 '14 at 03:49
  • @jack, the MSDN code is limited; however, I'm not sure the word 'fail' is exactly accurate. – Mahonri Moriancumer May 04 '14 at 04:01
  • By 'fail' I mean, it does use MAX_PATH which is < than supported nowadays (as you mentioned): 32,767 I think some directories willn't get printed correctly because only MAX_PATH-1 from it was actually copied. Is not this right? – Jack May 04 '14 at 04:07
  • 1
    Note that it's only NTFS that supports > MAX_PATH length paths, and only if you prefix the path with \\?\. Standard Win32 APIs will reject longer paths without this prefix so it's not strictly accurate to say it's only relevant for 16-bit apps (who uses 16-bit apps any more?) – Jonathan Potter May 04 '14 at 06:31
  • 3
    Where is the 32767 limit defined? What limits it? – david.pfx May 04 '14 at 11:00
  • @JonathanPotter well people use command line sometimes, and most of apps there are 16 bit. – ScienceDiscoverer Jul 02 '22 at 16:39