Curious
Curious

Reputation: 921

c++ array copy showing errors in vc++

int a[4] = {10,20,30,40};
std::vector<int> vec(4);
std::copy(a, a + 4, vec.begin());

I'm getting the following errorin vc++, it says warning but flagged as error how shall I solve this ?

Severity Code Description Project File Line Suppression State 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' ConsoleApplication3 e:\programs\vc\include\xutility 2372

Upvotes: 5

Views: 7755

Answers (2)

eerorika
eerorika

Reputation: 238311

A safe way to call copy without risk of making a mistake with the size. I would presume that the compiler wouldn't warn about this:

int a[] = {10,20,30,40};
std::vector<int> vec;
std::copy(std::begin(a), std::end(a), std::back_inserter(vec));

Your code, while not perfect, is well formed and a standard compliant compiler should compile it. Perhaps you have enabled an option that treats warnings as errors.

The warning message describes how to disable the warning.

Upvotes: 3

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275260

By default, MSVC deprecate certain APIs it deems unsafe. Basically, raw memory access where a mistake in a single parameter could lead to buffer overruns on the reading or writing side.

Among them is std::copy.

Calling a deprecated API leads to MSVC generating an error message.

You can disable this deprecation with -D_SCL_SECURE_NO_WARNINGS as the error suggests.

This may solve your problem; it involves wrapping the raw pointer with a "checked array iterator", which means that (at least in debug) you get assertions and/or exceptions instead of memory corruption if you get it wrong.

Buffer overruns are one of the more pervasive errors in C/C++ applications; treat them as a serious problem, even if it has runtime cost, unless and until you prove that a given path is performance critical. At that point, find a way to statically prove your array sizes are correct.

Upvotes: 8

Related Questions