How do the safe versions of the Microsoft C ++ C library functions know the size of static buffers?
While using some of Microsoft's safe versions of many of the standard C library functions, I have noticed that some of these functions seem to be able to determine at compile time if the buffer passed to the buffer is allocated statically or dynamically. If the input buffer is statically allocated, the function can determine its size automatically, but if the dynamic size must be specified as another parameter.
For example, this segment of code works when the buffer is statically allocated:
char buffer[1024];
sprintf_s(buffer, "Hello World\n");
printf_s(buffer);
However, this does not happen:
char *buffer = new char[1024];
sprintf_s(buffer, "Hello World\n");
printf_s(buffer);
I've tried looking for function definitions for these, but it's basically a preprocessor that's very confusing to try and follow.
So my question is, how is this defined and is it a standard C / C ++ language feature or some feature of Microsoft?
Also some of these functions seem to be pointless, as printf_s () has the same function definition as printf (), so why do they even have that?
If anyone can shine a light on this light, I would appreciate it.
source to share
If you look at the reference documentation for sprintf_s, _sprintf_s_l, swprintf_s, _swprintf_s_l , you will find the following declarations:
int sprintf_s(
char *buffer,
size_t sizeOfBuffer,
const char *format [,
argument] ...
);
template <size_t size>
int sprintf_s(
char (&buffer)[size],
const char *format [,
argument] ...
); // C++ only
With overloading, the compiler can determine the size of the array by passing in a static size array. This is standard C ++, nothing special at Microsoft (other than overloading and naming).
For more information, see Secure Template Forwarded and Parameter Validation .
source to share
There is a Microsoft macro called _countof that will give the size of static arrays. This is probably used when implementing secure printing related functions. According to this answer , there is a non-macro C ++ 11 way (get the size of a static array).
source to share
these functions seem to be able to determine at compile time if the passed in the buffer is statically or dynamically allocated
This is not true.
This is a simple example of using the type system; in one case, you are passing an array (and, remember, array types include dimension!). In another, you are passing a pointer.
This pointer could be to a piece of cheese isolated using stellar radiation for all compilers.
source to share