如何处理“缓冲太小” c ++中的异常 [英] how to handle "Buffer too small" exception in c++

查看:119
本文介绍了如何处理“缓冲太小” c ++中的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,



请找到以下代码,



Hi there,

please find the below code,

char l_Title_ca[10];
try{
	 sprintf_s(l_Title_ca,"Version %d.%02d [MemberId :- %s]",Ver,Rel,MemID);
 }
catch(char* str)
{
     cout << "error: ";
    // if(errn == BUFFER_TOO_SMALL)
     {
          cout << "storage buffer too small.\n";
          return 0;
     }
}catch(...)
{
	cout<<"caught..."<<endl;
} 





在运行时执行代码时,我收到错误消息缓冲区太小而无法使用上述方法捕获异常。



请任何人可以指导我如何捕获异常?



问候,

Ranjith



while executing the code at runtime, i am getting the error message "buffer too small" and not able to catch the exception using above method.

Please any can guide me how can i catch the exception?

Regards,
Ranjith

推荐答案

hi,

sprintf_s的第二个参数应该是一个整数值。 以此为例 [ ^ ]



希望这有帮助!

the second argument of sprintf_s should be some integer value. Take a look here for example[^]

hope this helps !


sprintf_s()不会抛出异常。相反,无效的参数处理程序 [ ^ ]。要更改行为,您可以使用 _set_invalid_parameter_handler 安装自己的处理程序[ ^ ]。
sprintf_s() is not throwing exceptions. Instead the Invalid Parameter Handler[^] is called when the buffer is too small. To change the behaviour you can install your own handler with _set_invalid_parameter_handler[^].


简单提供更大的缓冲区。如果你真的想写一个错误,请检查字符串的长度,并使用一个稍微大一点的缓冲区,让你真正想要允许。



例如,如果缓冲区大小是11,那么如果字符串的长度是10,那么你知道格式化的字符串太大而不能达到最大所需大小。



另一方面如果字符串大小没有限制,那么您可以考虑使用C ++代码创建字符串(如字符串流)或相对较大的缓冲区,以便它总是足以处理有效的情况。



通常在上面的情况下你可能应该知道每个部分的最大长度......因此你能够找出所需的缓冲区大小以便出错永远不会发生,因为缓冲区对于最坏的情况来说足够大。
Simply provide a bigger buffer. If you really want to write an error the check the length of the string and use a buffer slight bigger that want you really want to allows.

For example, if the buffer size is 11, then if the length of the string is 10, then you know that the formated string is too big to fit maximum desired size.

On the other hand, if there are no limit on string size, then you might consider using C++ code to create the string (like a string stream)or a relatively large buffer so that it would always be big enough to handled valid case.

Typically in a case like the one above you probably should have an idea of the maximum length of each part... thus you be able to figure out required buffer size so that an error would never occurs because the buffer would be big enough for the worst case.


这篇关于如何处理“缓冲太小” c ++中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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