简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM