Skip to content

Commit 16ea72e

Browse files
committed
build: fix snprintf() usage
1 parent 235f2cc commit 16ea72e

File tree

1 file changed

+27
-5
lines changed

1 file changed

+27
-5
lines changed

modules/core/src/system.cpp

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -751,15 +751,20 @@ String format( const char* fmt, ... )
751751
{
752752
va_list va;
753753
va_start(va, fmt);
754-
int bsize = static_cast<int>(buf.size()),
755-
len = vsnprintf((char *)buf, bsize, fmt, va);
754+
int bsize = static_cast<int>(buf.size());
755+
#if defined _MSC_VER && __cplusplus < 201103L
756+
int len = _vsnprintf_s((char *)buf, bsize, _TRUNCATE, fmt, va);
757+
#else
758+
int len = vsnprintf((char *)buf, bsize, fmt, va);
759+
#endif
756760
va_end(va);
757761

758762
if (len < 0 || len >= bsize)
759763
{
760764
buf.resize(std::max(bsize << 1, len + 1));
761765
continue;
762766
}
767+
buf[bsize - 1] = 0;
763768
return String((char *)buf, len);
764769
}
765770
}
@@ -851,6 +856,22 @@ bool setBreakOnError(bool value)
851856
return prevVal;
852857
}
853858

859+
static bool cv_snprintf(char* buf, int len, const char* fmt, ...)
860+
{
861+
va_list va;
862+
va_start(va, fmt);
863+
#if defined _MSC_VER && __cplusplus < 201103L
864+
int res = _vsnprintf_s((char *)buf, len - 1, _TRUNCATE, fmt, va);
865+
va_end(va);
866+
buf[len - 1] = 0;
867+
return res >= 0 && res < len - 1;
868+
#else
869+
int res = vsnprintf((char *)buf, len, fmt, va);
870+
va_end(va);
871+
return res >= 0 && res < len;
872+
#endif
873+
}
874+
854875
void error( const Exception& exc )
855876
{
856877
if (customErrorCallback != 0)
@@ -861,10 +882,10 @@ void error( const Exception& exc )
861882
const char* errorStr = cvErrorStr(exc.code);
862883
char buf[1 << 12];
863884

864-
snprintf( buf, sizeof(buf),
865-
"OpenCV Error: %s (%s) in %s, file %s, line %d",
885+
cv_snprintf(buf, sizeof(buf),
886+
"OpenCV Error: %s (%s) in %s, file %s, line %d",
866887
errorStr, exc.err.c_str(), exc.func.size() > 0 ?
867-
exc.func.c_str() : "unknown function", exc.file.c_str(), exc.line );
888+
exc.func.c_str() : "unknown function", exc.file.c_str(), exc.line);
868889
fprintf( stderr, "%s\n", buf );
869890
fflush( stderr );
870891
# ifdef __ANDROID__
@@ -886,6 +907,7 @@ void error(int _code, const String& _err, const char* _func, const char* _file,
886907
error(cv::Exception(_code, _err, _func, _file, _line));
887908
}
888909

910+
889911
ErrorCallback
890912
redirectError( ErrorCallback errCallback, void* userdata, void** prevUserdata)
891913
{

0 commit comments

Comments
 (0)