Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do Microsoft's C++ safe versions of C library functions know the size of static buffers?

Tags:

c++

c

static

crt

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.

like image 461
Matt Avatar asked Sep 02 '25 09:09

Matt


1 Answers

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).


Additional information is available under Secure Template Overloads as well as Parameter Validation.
like image 70
IInspectable Avatar answered Sep 04 '25 23:09

IInspectable