When and why can sprintf fail?

给你一囗甜甜゛ 提交于 2019-12-05 11:55:07

From the c99 standard:

The sprintf function returns the number of characters written in the array, not counting the terminating null character, or a negative value if an encoding error occurred.

This generally happens only with the multi-byte and wide character character set functions.

It may fail with wrong format string, for example, which cannot happen in your case.

If buffer is not big enough, it may.

Otherwise, no reason for it to fail.

In UNIX, it can fail:

 EILSEQ
       A wide-character code that does not  correspond  to  a
       valid character has been detected.

 EINVAL
       There are insufficient arguments.

EILSEQ has already been mentioned.

It may also fail, SIGSEGV, when the format specifier does not match the data - example using a %s format specifier with an int, 32 bit example:

int pdq=0xffffffff;
char tmp[32]={0x0};

sprintf(tmp, "%s", pdq);

I believe there is another case where snprintf() cannot succeed. It does not appear to be mentioned in POSIX or the current Linux manpage.

Upon successful completion, the snprintf() function shall return the number of bytes that would be written to s had n been sufficiently large excluding the terminating null byte.

snprintf() returns int. But an input string could be larger than INT_MAX.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!