While using some of the Microsoft safe versions of many of the standard C library functions I've noticed that some of these functions seem capable of determining at compile time if a passed in buffer is allocated statically or dynamically. If the input buffer is statically allocated the function can determine the size of it auto-magically but if dynamic the size must be given 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 one does not:
char *buffer = new char[1024];
sprintf_s(buffer, "Hello World\n");
printf_s(buffer);
I've tried looking at the function definitions for these but the code is mostly preprocessor defines that are very confusing to try to follow.
So my question is: how is this being determined and is this a standard C / C++ language feature or some kind of Microsoft specific feature?
Also some of these functions seem pointless like printf_s() has the exact same function definition as printf(), so why do they even have this?
If anyone can shine some light on this I'd appreciate it.
If you take a look at the reference documentation for sprintf_s, _sprintf_s_l, swprintf_s, _swprintf_s_l, you'll 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 the overload the compiler can determine the array size, when passed a statically sized array. This is standard C++, nothing Microsoft specific here (except for the overload and naming).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With