以下代码会导致错误并杀死我的应用程序.缓冲区只有10个字节长,文本长度为22个字节(缓冲区溢出)是有道理的.
char buffer[10]; int length = sprintf_s( buffer,10,"1234567890.1234567890." );
我如何抓住这个错误,所以我可以报告它,而不是崩溃我的应用程序?
编辑:
阅读下面的评论后,我用_snprintf_s.如果返回-1值,则缓冲区未更新.
length = _snprintf_s( buffer,9,"123456789" ); printf( "1) Length=%d\n",length ); // Length == 9 length = _snprintf_s( buffer,"1234567890.1234567890." ); printf( "2) Length=%d\n",length ); // Length == -1 length = _snprintf_s( buffer,"1234567890.1234567890." ); printf( "3) Length=%d\n",length ); // Crash,it needs room for the NULL char
解决方法
您可以使用snprintf(Windows上的a.k.a _snprintf)而不是sprintf_s.
#ifdef WIN32 #define snprintf _snprintf #endif char buffer[10]; int length = snprintf( buffer,"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 */ }