Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does sprintf_s avoid buffer overflow issue

Visual Studio prompts me to replace sprintf with sprintf_s, instead of snprintf.

sprintf_s does not require a length parameter, how does it avoid buffer overflow issue?

like image 343
daisy Avatar asked Apr 22 '26 21:04

daisy


1 Answers

There are 2 versions. One template version which tries to deduce the size of the buffer and one where you pass the size.

int sprintf_s<_Size>(char (&_Dest)[_Size], const char *_Format, ...)
int sprintf_s(char * _DestBuf, size_t _SizeInBytes, const char *_Format, ...)

If the first one cannot be deduced, you will have to pass the size yourself

So this:

char buf[100];

sprintf_s(buf, "%d", 1);

Will instantiate a function template

sprintf_s<100>();

This will generate a compiler error:

char *buf = new char[100];

sprintf_s(buf, "%", 1);

And you have to use the other version to make it compile:

sprintf_s(buf, 100, "%d", 1);
like image 147
Serve Laurijssen Avatar answered Apr 25 '26 15:04

Serve Laurijssen