0

As of Visual Studio 2005, the CRT has replaced most string functions with secure versions which add a size argument to indicate the limits of the destination buffer(s). This is fine, but it’s not clear how it should be used. Does it include the terminating zero? Take the following code for example:

…
TCHAR path[MAX_PATH] = TEXT("");
_tcscpy_s(path, MAX_PATH, filename);
…

Is it okay or does it induce an off-by-one error?

Synetech
  • 9,643
  • 9
  • 64
  • 96
  • These functions were added to prevent buffer overflow. So you always specify the buffer size. – Hans Passant Jul 01 '14 at 17:11
  • Yes, I know, but I’m not asking about buffer overflows specifically (putting in too much data), but about off-by-one errors. They don’t make it clear if the size should include the terminating zero or not. For example, the remarks for [`strcpy_s`](http://msdn.microsoft.com/en-us/library/td1esda9.aspx) passively imply that the size includes the terminating zero, but it doesn’t actually mention the zero in regards to the size argument. In my example, I *did* specify the buffer size, but should the `_s` function be getting `MAX_PATH` or `MAX_PATH-1` (or even `MAX_PATH+1`)? – Synetech Jul 01 '14 at 19:44

1 Answers1

0

It'd be a failure of the API design to be MAX_PATH+/-1, as that would be confusing and lead to more buffer overflows.

Documentation states clearly for dest[10] that _countof(dest) should be used, which would be 10 So a simple MAX_PATH will suffice.

Jonathan
  • 6,741
  • 7
  • 52
  • 69