sprintf_s缓冲区太小 [英] sprintf_s with a buffer too small

查看:684
本文介绍了sprintf_s缓冲区太小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码会导致错误并杀死我的应用程序。缓冲区只有10个字节长,文本长度为22个字节(缓冲区溢出)是有道理的。

The following code causes an error and kills my application. It makes sense as the buffer is only 10 bytes long and the text is 22 bytes long (buffer overflow).

char buffer[10];    
int length = sprintf_s( buffer, 10, "1234567890.1234567890." ); 

如何抓住这个错误,以便我可以报告错误,而不是崩溃我的应用程序?

How do I catch this error so I can report it instead of crashing my application?

编辑:

阅读下面的评论后,我用_snprintf_s。如果它返回一个-1值,那么缓冲区没有更新。

After reading the comments below I went with _snprintf_s. If it returns a -1 value then the buffer was not updated.

length = _snprintf_s( buffer, 10, 9, "123456789" );
printf( "1) Length=%d\n", length ); // Length == 9

length = _snprintf_s( buffer, 10, 9, "1234567890.1234567890." );
printf( "2) Length=%d\n", length ); // Length == -1

length = _snprintf_s( buffer, 10, 10, "1234567890.1234567890." );
printf( "3) Length=%d\n", length ); // Crash, it needs room for the NULL char 


推荐答案

而不是 sprintf_s ,您可以使用 snprintf (又名 _snprintf 在窗口上)

Instead of sprintf_s, you could use snprintf (a.k.a _snprintf on windows).

#ifdef WIN32
#define snprintf _snprintf
#endif

char buffer[10];    
int length = snprintf( buffer, 10, "1234567890.1234567890." );
// unix snprintf returns length output would actually require;
// windows _snprintf returns actual output length if output fits, else negative
if (length >= sizeof(buffer) || length<0) 
{
    /* error handling */
}

这篇关于sprintf_s缓冲区太小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆