std::copy 등의 함수 사용 시 _SCL_SECURE_NO_WARNINGS 에러 발생
std::copy를 다음과 같이 사용하면,
#include "stdafx.h"
#include <algorithm>
void func1()
{
int a[] = { 1, 2, 3 };
int b[3];
std::copy(a, a + 3, b);
}
컴파일 에러가 없지만 포인터로 바꾸면,
void func1()
{
int a[] = { 1, 2, 3 };
int *b = new int[3];
std::copy(a, a + 3, b);
}
다음과 같은 오류가 발생합니다.
Error C4996 'std::copy::_Unchecked_iterators::_Deprecate': Call to 'std::copy' with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators' ConsoleApplication1 c:\program files (x86)\microsoft visual studio\2017\enterprise\vc\tools\msvc\14.11.25503\include\xutility 2294
왜냐하면, Buffer Overflow에 민감한 마이크로소프트는 이를 유발할 수 있는 함수들을 전부 "unsafe"로 규정해 "_Deprecate"로 처리했기 때문입니다.
template<class _InIt,
class _OutIt> inline
_OutIt copy(_InIt _First, _InIt _Last,
_OutIt _Dest)
{ // copy [_First, _Last) to [_Dest, ...)
_DEPRECATE_UNCHECKED(copy, _Dest);
return (_Copy_no_deprecate(_First, _Last, _Dest));
}
즉, std::copy의 3번째 인자로 전달된 b 버퍼의 크기를 알 수 없기 때문에 복사 과정에서 b 버퍼의 크기를 넘는 보안 취약점이 발생하는 것입니다.
이 오류를 벗어나는 5가지 방법을 다음의 글에서 소개하고 있습니다.
Why am I getting these _SCL_SECURE_NO_WARNINGS messages?
; https://blogs.msdn.microsoft.com/vcblog/2017/05/05/why-am-i-getting-these-_scl_secure_no_warnings-messages/
가장 쉬운 방법은 전역 헤더 파일에 _SCL_SECURE_NO_WARNINGS 상수를 정의하는 것입니다.
#define _SCL_SECURE_NO_WARNINGS
이렇게 하면 기존의 소스 코드를 전혀 변경하지 않고 컴파일할 수 있습니다. 단지, 보안 취약점은 여전히 안고 간다는 문제가 있습니다. 소스 코드를 변경할 수 있다면 다음의 stdext 네임스페이스에 있는 함수를 쓰는 방법이 있습니다.
#include <iterator>
void func1()
{
int a[] = { 1, 2, 3 };
int *b = new int[3];
std::copy(a, a + 3, stdext::checked_array_iterator<int *>(b, 3));
}
보는 바와 같이 checked_array_iterator는 b 버퍼의 크기가 3임을 알 수 있으므로 안전한 iterator를 반환하게 됩니다.
[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]