过小的缓冲sprintf_s [英] sprintf_s with a buffer too small

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

问题描述

以下code会导致错误并杀死我的申请。是有意义的缓冲器仅为10字节长,所述文本是22字节长(缓冲区溢出)。

 字符缓冲区[10];
INT长度= sprintf_s(缓冲液,10,1234567890.1234567890。);

我如何赶上这个错误,所以我可以举报,而不是崩溃我的应用程序?

编辑:

阅读下面的评论我_snprintf_s去后。如果返回-1值则缓冲区没有更新。

 长度= _snprintf_s(缓冲,10,9,123456789);
的printf(1)长度=%d个\\ N,长度); //长度== 9长度= _snprintf_s(缓冲液,10,第9,1234567890.1234567890。);
的printf(2)长度=%d个\\ N,长度); //长度== -1长度= _snprintf_s(缓冲液,10,10,1234567890.1234567890。);
的printf(3)长度=%d个\\ N,长度); //崩溃,它需要的空间的NULL字符


解决方案

而不是 sprintf_s ,你可以使用的snprintf (又名 _snprintf 在Windows上)。

 的#ifdef WIN32
#定义的snprintf _snprintf
#万一炭缓冲液[10];
INT长度= snprintf的(缓冲液,10,1234567890.1234567890。);
// UNIX的snprintf返回长度产量将要求;
//窗口_snprintf返回如果输出适合实际输出长度,否则负
如果(长度&GT = sizeof的(缓冲器)||长度℃下)
{
    / *错误处理* /
}

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?

Edit:

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

解决方案

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天全站免登陆