Visual C++: C4996 Warning on Copy with Array Parameters

Visual C++ throws a C4996 warning if std::copy is called with array parameters (instead of the conventional iterator parameters). For example, if you have code of the form:

std::copy( arr0, arr0 + 5, arr1 );

where arr0 and arr1 are pointers to arrays or valid memory locations.

The C4996 warning is of the form:

warning C4996: ‘std::_Copy_impl’: Function call 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’

Visual C++ uses checked iterators by default everywhere for security reasons. This warning is a manifestation of that design decision. There are a few ways to deal with it:

  • checked_array_iterator: A checked_array_iterator can be used to wrap the unsafe array pointer. It is a Microsoft extension to the C++ Standard and is defined in the stdext namespace. It results in an assertion check at runtime, which throws an exception if it fails. Applying a checked_array_iterator on the above code:
    #include <iterator>
    std::copy( arr0, arr0 + 5, stdext::checked_array_iterator<int*>( arr1, 5 ) );
  • unchecked_copy: The copy call can be replaced with an unchecked_copy if you want to forgo the checking. This is defined in the stdext namespace. Note that this is usable in Visual C++ 2008 and not later. It was removed in Visual C++ 2010. Using unchecked_copy instead of copy:
    stdext::unchecked_copy( arr0, arr0 + 5, arr1 );
  • vector: Another solution is to wrap the destination array in a vector and use the vector as the destination of copy. Not a great solution, but it might work for you.
  • pragma warning: Turn off the C4996 warning for the call to copy using pragma warning. This can be applied at the source file level to mask all C4996 warnings. Note that this is a really bad move since it masks all deprecation warnings!
  • _SCL_SECURE_NO_WARNINGS: Define the _SCL_SECURE_NO_WARNINGS macro to turn off all C4996 warnings. SCL here stands for Standard C++ Library. Again, turning off this warning not a good move! If you want to do this anyway, add -D_SCL_SECURE_NO_WARNINGS to your project settings or #define _SCL_SECURE_NO_WARNINGS in your code.

2 thoughts on “Visual C++: C4996 Warning on Copy with Array Parameters

  1. Thanks for this. Porting over cross-platform code.
    I decided to use your first solution:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.